code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
<template>
<div class="login-container">
<div style="width: 400px; margin: 130px auto; position: absolute; left: 35%;">
<div style="color: black; font-size: 40px; text-align: center; padding: 30px 0">登 录</div>
<el-form ref="form" :model="form" :rules="rules" size="large">
<el-form-item prop="username">
<el-input v-model="form.username" clearable prefix-icon="avatar" placeholder="用户名"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input v-model="form.password" clearable prefix-icon="lock" show-password placeholder="密码"></el-input>
</el-form-item>
<el-form-item :model="form" prop="identity">
<el-radio v-model="form.identity" label="tenant" style="color: grey">租客</el-radio>
<el-radio v-model="form.identity" label="landlord" style="color: grey">房东</el-radio>
<el-radio v-model="form.identity" label="admin" style="color: grey">管理员</el-radio>
</el-form-item>
<el-form-item>
<el-button :disabled="disabled" style="width: 30%; margin-left: 45%; font-size: 15px;" type="success" @click="goToFaceRecognition">人脸识别登录</el-button>
<el-button :disabled="!disabled" style="width: 20%; margin-left: auto; font-size: 15px;" type="primary" @click="login">登 录</el-button>
</el-form-item>
</el-form>
<div style="text-align: left; margin-top: -65px;">
<router-link to="/Register">
<el-link underline="never" type="primary" class="register-link">未注册?点击注册</el-link>
</router-link>
</div>
</div>
</div>
<div class="footer">
©Copyright 2025 UPC, Edu.
</div>
</template>
<script src="@/assets/js/Login.js"></script>
<style scoped>
.login-container {
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: linear-gradient(
135deg,
hsl(170deg, 80%, 70%),
hsl(190deg, 80%, 70%),
hsl(250deg, 80%, 70%),
hsl(320deg, 80%, 70%),
hsl(320deg, 80%, 70%),
hsl(250deg, 80%, 70%),
hsl(190deg, 80%, 70%),
hsl(190deg, 80%, 70%),
hsl(170deg, 80%, 70%)
);
background-size: 600%;
animation: animation 15s linear infinite;
}
@keyframes animation {
0% {
background-position: 0 0;
}
100% {
background-position: 100% 100%;
}
}
.register-link {
color: grey;
}
.register-link:hover {
color: rgb(0, 110, 255);
}
.register-link:active {
color: rgb(0, 76, 255);
}
.footer {
left: 0;
bottom: 0;
color: #fff;
width: 100%;
position: absolute;
text-align: center;
line-height: 30px;
padding-bottom: 10px;
text-shadow: #000 0.1em 0.1em 0.1em;
font-size: 14px;
}
.footer a,
.footer span {
color: #fff;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/Login.vue
|
Vue
|
unknown
| 3,150
|
<template>
<div class="login-container">
<div style="width: 400px; margin: 130px auto; position: absolute; left: 35%;">
<div style="color: black; font-size: 40px; text-align: center; padding: 30px 0">登 录</div>
<el-form ref="form" :model="form" :rules="rules" size="large">
<el-form-item prop="username">
<el-input v-model="form.username" clearable prefix-icon="avatar" placeholder="用户名"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input v-model="form.password" clearable prefix-icon="lock" show-password placeholder="密码"></el-input>
</el-form-item>
<el-form-item :model="form" prop="identity">
<el-radio v-model="form.identity" label="tenant" style="color: grey">租客</el-radio>
<el-radio v-model="form.identity" label="landlord" style="color: grey">房东</el-radio>
<el-radio v-model="form.identity" label="admin" style="color: grey">管理员</el-radio>
</el-form-item>
<el-form-item>
<el-button :disabled="!disabled" style="width: 20%; margin-left: auto; font-size: 15px;" type="primary" @click="login">登 录</el-button>
</el-form-item>
</el-form>
<div style="text-align: left; margin-top: -65px;">
<router-link to="/Register">
<el-link underline="never" type="primary" class="register-link">未注册?点击注册</el-link>
</router-link>
</div>
</div>
</div>
<div class="footer">
©Copyright 2025 UPC, Edu.
</div>
</template>
<script src="@/assets/js/Login.js"></script>
<style scoped>
.login-container {
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: linear-gradient(
135deg,
hsl(170deg, 80%, 70%),
hsl(190deg, 80%, 70%),
hsl(250deg, 80%, 70%),
hsl(320deg, 80%, 70%),
hsl(320deg, 80%, 70%),
hsl(250deg, 80%, 70%),
hsl(190deg, 80%, 70%),
hsl(190deg, 80%, 70%),
hsl(170deg, 80%, 70%)
);
background-size: 600%;
animation: animation 15s linear infinite;
}
@keyframes animation {
0% {
background-position: 0 0;
}
100% {
background-position: 100% 100%;
}
}
.register-link {
color: grey;
}
.register-link:hover {
color: rgb(0, 110, 255);
}
.register-link:active {
color: rgb(0, 76, 255);
}
.footer {
left: 0;
bottom: 0;
color: #fff;
width: 100%;
position: absolute;
text-align: center;
line-height: 30px;
padding-bottom: 10px;
text-shadow: #000 0.1em 0.1em 0.1em;
font-size: 14px;
}
.footer a,
.footer span {
color: #fff;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/Login1.vue
|
Vue
|
unknown
| 2,947
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/landlordHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item :to="{ path: '/LandlordHouse' }">我的房源</el-breadcrumb-item>
<el-breadcrumb-item>房源信息展示</el-breadcrumb-item>
<router-link to="/LandlordHouse" style="position: relative; right: -72%;">
<el-button type="primary" style="width: 55px; height: 33px; font-size: 14px; font-family: 'Segoe UI'; border-radius: 10px;">返回</el-button>
</router-link>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div class="common-layout">
<el-container>
<el-header>
<h1 style="font-size: 26px; font-weight: bold; text-align: center; ">{{ Data.title }}</h1>
<el-tag
:type="getStatusTagType(Data.status)"
size="large" style="position: relative; left: 94%; top: -57%; font-weight: bold; font-size: 14px;">
{{ getStatusLabel(Data.status) }}
</el-tag>
</el-header>
<el-container>
<el-aside width="500px">
<el-image :src="Data.imageUrl" fit="fill" style="width: 100%; height: 100%; border-radius: 10px;"></el-image>
</el-aside>
<el-main>
<el-col :gutter="20" style="margin-top: -20px;">
<el-row :span="8"><p><strong>住房名称:</strong>{{ Data.title }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房编号:</strong>{{ Data.houseId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>房东编号:</strong>{{ Data.landlordId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>所在地区:</strong>{{ Data.area }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>地址:</strong>{{ Data.address }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房描述:</strong>{{ Data.description }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房面积:</strong>{{ Data.size }} 平方米</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>户型:</strong>{{ Data.roomCount }} 居室</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>楼层:</strong>{{ Data.floor }} 层</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>租金:</strong>{{ Data.price }} 元/月</p></el-row>
</el-col>
</el-main>
</el-container>
<!-- 评论区 -->
<el-main style="margin-top: 20px;">
<div style="display: flex; align-items: center; margin-bottom: 15px;">
<h2 style="font-size: 20px; font-weight: bold;">用户评论 ({{ commentCount }})</h2>
<div class="line" style="margin-left: 1.5%; flex: 1; height: 1px; background-color: #eee;"></div>
</div>
<!-- 评论列表(评论数>0时显示) -->
<div v-if="comments.length > 0">
<div
v-for="comment in comments"
:key="comment.id"
style="margin-bottom: 15px; padding: 15px; border: 1px solid #ebeef5; border-radius: 4px;"
>
<!-- 评论头部:用户信息+评分+时间 -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<div>
<span style="font-weight: 600; color: #303133;">{{ userMap[comment.tenantId] || '匿名用户' }}</span>
<el-rate
v-model="comment.rating"
disabled
:colors="['#99A9BF', '#F7BA1E', '#FF9900']"
style="margin-left: 10px;"
/>
</div>
<span style="font-size: 12px; color: #909399;">{{ formatDate(comment.commentTime) }}</span>
</div>
<!-- 评论内容 -->
<div style="color: #606266; line-height: 1.6;">{{ comment.content }}</div>
</div>
</div>
<!-- 暂无评论(评论数=0时显示) -->
<div v-else style="text-align: center; padding: 50px 0; color: #909399;">
暂无评论
</div>
</el-main>
</el-container>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/HouseDisplay.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/MyHouseDisplay.vue
|
Vue
|
unknown
| 4,739
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好,用户 {{ username }} !欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/tenantHome">首页</el-menu-item>
<el-menu-item index="/TenantFavorite">我的收藏</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/TenantApplication">我的申请</el-menu-item>
<el-menu-item index="/TenantRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/SelectHouse">查看房源</el-menu-item>
<el-menu-item index="/VectorDatabase">向量数据库</el-menu-item>
<el-menu-item index="/PersonalAssistant">RAG问答助手</el-menu-item>
<el-menu-item index="/GraphRAGAssistant">GraphRAG问答助手</el-menu-item>
<el-menu-item index="/TenantSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-main>
<el-card id="personal-info-card" style="margin: 5px; min-height: calc(100vh - 110px);">
<h1 style="text-align: center;">RAG问答助手</h1>
<h2 style="text-align: center;">为您解答关于房源信息的一切问题!</h2>
<div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
<div class="chat-container" id="chatContainer"></div>
<div class="input-area">
<input type="text" id="questionInput" placeholder="请输入您的问题..." />
<select id="documentSelect">
<option value="house1">house1</option>
</select>
<select id="chunkTypeSelect">
<option value="recursive">递归分块</option>
<option value="semantic">语义分块</option>
</select>
<button @click="askQuestion">发送</button>
</div>
</el-card>
</el-main>
</el-container>
</div>
</div>
</template>
<script>
import request from "@/axios/request";
import request3 from "@/axios/request3";
import request4 from "@/axios/request4";
import { ElMessage } from 'element-plus';
export default {
data() {
return {
loading: true,
loadingHouses: false,
saving: false,
tenantId: '',
username: '',
password: '',
phone: '',
email: '',
selectedHouse: '',
houseOptions: [],
allHouses: [],
chunkMethod: '',
checkMode: '',
chunkCheckTimer: null,
summaryData: '',
structureData: '',
chunkData: '',
activeIndex: '/PersonalAssistant'
};
},
mounted() {
this.fetchUserInfo();
this.loadAllHouses();
this.loadVectorDatabase();
// 回车键发送
this.$nextTick(() => {
const questionInput = document.getElementById('questionInput');
if (questionInput) {
questionInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.askQuestion();
}
});
}
// 页面加载完成后获取文档列表
this.loadDocuments();
});
},
beforeUnmount() {
if (this.chunkCheckTimer) {
clearInterval(this.chunkCheckTimer);
}
},
methods: {
async loadAllHouses() {
this.loadingHouses = true;
try {
const res = await request.get("/house/findAll");
if (res.code === 200) {
this.allHouses = res.data || [];
// 初始化时显示所有房源
this.houseOptions = this.allHouses.map(item => ({
houseId: item.houseId,
title: item.title
}));
} else {
ElMessage.error(res.msg || "加载房源数据失败");
}
} catch (err) {
console.error("加载房源数据错误:", err);
ElMessage.error("网络错误,请稍后再试");
} finally {
this.loadingHouses = false;
}
},
async loadVectorDatabase() {
this.$watch('checkMode', async (newVal) => {
this.summaryData = '';
this.structureData = '';
this.chunkData = '';
if (newVal === 'summary') {
try {
const res = await request3.get('/vector/summary');
if (res.code === 200) {
console.log('摘要数据:', res.data);
this.summaryData = JSON.stringify(res.data, null, 2);
} else {
ElMessage.error(res.msg || "获取摘要数据失败");
}
} catch (err) {
console.error("获取摘要数据错误:", err);
ElMessage.error("网络错误,请稍后再试");
}
} else if (newVal === 'structure') {
try {
const res = await request3.get('/vector/structure');
if (res.code === 200) {
console.log('结构数据:', res.data);
this.structureData = JSON.stringify(res.data, null, 2);
} else {
ElMessage.error(res.msg || "获取结构数据失败");
}
} catch (err) {
console.error("获取结构数据错误:", err);
ElMessage.error("网络错误,请稍后再试");
}
} else if (newVal === 'chunk') {
this.checkChunkRequirements();
}
});
this.$watch('selectedHouse', () => {
if (this.checkMode === 'chunk') {
this.checkChunkRequirements();
}
});
this.$watch('chunkMethod', () => {
if (this.checkMode === 'chunk') {
this.checkChunkRequirements();
}
});
},
async checkChunkRequirements() {
if (this.chunkCheckTimer) {
clearInterval(this.chunkCheckTimer);
}
const checkAndLoad = async () => {
if (!this.selectedHouse && this.checkMode === 'chunk') {
ElMessage.warning("请选择房源");
return false;
}
if (!this.chunkMethod && this.checkMode === 'chunk') {
ElMessage.warning("请选择分块方式");
return false;
}
try {
const res = await request3.post('/vector/chunk', {
params: {
title: this.selectedHouse,
chunkMethod: this.chunkMethod
}
});
if (res.code === 200) {
console.log('分块内容数据:', res.data);
this.chunkData = JSON.stringify(res.data, null, 2);
if (this.chunkCheckTimer) {
clearInterval(this.chunkCheckTimer);
this.chunkCheckTimer = null;
}
return true;
} else {
ElMessage.error(res.msg || "获取分块内容失败");
return false;
}
} catch (err) {
console.error("获取分块内容错误:", err);
ElMessage.error("网络错误,请稍后再试");
return false;
}
};
const success = await checkAndLoad();
if (!success) {
this.chunkCheckTimer = setInterval(checkAndLoad, 10000);
}
},
async fetchUserInfo() {
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
if (token && token.tenantId) {
const tenantId = token.tenantId;
const res = await request.get(`/tenant/findById/${tenantId}`);
if (res.code === 200) {
token = res.data;
} else {
ElMessage.error("获取用户信息失败");
}
console.log(token);
if (!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.tenantId = token.tenantId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
}
},
// 搜索房源
searchHouses(query) {
if (!query) {
this.houseOptions = this.allHouses.map(item => ({
houseId: item.houseId,
title: item.title
}));
return;
}
const filteredHouses = this.allHouses.filter(item =>
(item.title).toLowerCase().includes(query.toLowerCase())
);
this.houseOptions = filteredHouses.map(item => ({
houseId: item.houseId,
title: item.title
}));
},
// 保存到文件
async saveToFile() {
if (!this.selectedHouse && this.checkMode === 'chunk') {
ElMessage.warning("请选择房源");
return;
}
if (!this.chunkMethod && this.checkMode === 'chunk') {
ElMessage.warning("请选择分块方式");
return;
}
if (!this.checkMode) {
ElMessage.warning("请选择查看目标");
return;
}
this.saving = true;
try {
const res = await request4.post('/vector/save', {
title: this.selectedHouse,
chunkMethod: this.chunkMethod,
checkMode: this.checkMode
});
if (res.code === 200) {
ElMessage.success("文件保存成功 (保存路径:D:\\Edge下载)");
} else {
ElMessage.error(res.msg || "保存失败");
}
} catch (err) {
console.error("保存文件错误:", err);
ElMessage.error("网络错误,请稍后再试");
} finally {
this.saving = false;
}
},
SignOut() {
sessionStorage.clear();
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({ path: '/Login' });
},
// 显示消息
showMessage(message, isUser = false) {
const chatContainer = document.getElementById('chatContainer');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${isUser ? 'user-message' : 'bot-message'}`;
messageDiv.textContent = message;
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
},
// 显示加载状态
showLoading() {
const chatContainer = document.getElementById('chatContainer');
const loadingDiv = document.createElement('div');
loadingDiv.className = 'message bot-message loading';
loadingDiv.id = 'loadingMessage';
loadingDiv.textContent = '正在思考中...';
chatContainer.appendChild(loadingDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
},
// 隐藏加载状态
hideLoading() {
const loadingMessage = document.getElementById('loadingMessage');
if (loadingMessage) {
loadingMessage.remove();
}
},
// 提问函数
async askQuestion() {
const questionInput = document.getElementById('questionInput');
const documentSelect = document.getElementById('documentSelect');
const chunkTypeSelect = document.getElementById('chunkTypeSelect');
// 检查元素是否存在
if (!questionInput || !documentSelect || !chunkTypeSelect) {
console.error('无法获取输入元素');
return;
}
const question = questionInput.value.trim();
const documentName = documentSelect.value;
const chunkType = chunkTypeSelect.value;
if (!question) {
alert('请输入问题');
return;
}
// 显示用户问题
this.showMessage(question, true);
questionInput.value = '';
// 显示加载状态
this.showLoading();
try {
// 发送请求到后端
const response = await fetch('http://localhost:8084/rag/query', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
question: question,
document_name: documentName,
chunk_type: chunkType
})
});
const data = await response.json();
this.hideLoading();
if (data.code === 200) {
// 显示回答
this.showMessage(data.data.answer);
// 显示参考资料(简化显示)
if (data.data.source_documents && data.data.source_documents.length > 0) {
let sourcesText = "参考资料:\n";
data.data.source_documents.slice(0, 2).forEach((doc, index) => {
sourcesText += `${index + 1}. ${doc.content.substring(0, 100)}...\n`;
});
this.showMessage(sourcesText);
}
} else {
this.showMessage(`错误: ${data.msg}`);
}
} catch (error) {
this.hideLoading();
this.showMessage(`网络错误: ${error.message}`);
}
},
async loadDocuments() {
try {
const response = await fetch('http://localhost:8084/rag/documents');
const data = await response.json();
if (data.code === 200) {
const documentSelect = document.getElementById('documentSelect');
if (documentSelect) {
documentSelect.innerHTML = '';
data.data.documents.forEach(doc => {
const option = document.createElement('option');
option.value = doc.name;
option.textContent = doc.name;
documentSelect.appendChild(option);
});
}
}
} catch (error) {
console.error('获取文档列表失败:', error);
}
}
}
};
</script>
<style scoped>
.background {
background-color: whitesmoke;
height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.el-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: #409EFF;
}
.line {
background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x;
height: 0.4rem;
flex: 1;
background-size: auto;
margin: 0.16rem;
}
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.chat-container {
border: 1px solid #ccc;
height: 400px;
overflow-y: auto;
padding: 10px;
margin-top: 10px;
margin-bottom: 20px;
background-color: #f9f9f9;
}
.chat-container ::v-deep .message {
margin-bottom: 10px;
padding: 8px;
border-radius: 4px;
max-width: 80%;
word-wrap: break-word;
}
.chat-container ::v-deep .user-message {
background-color: #dcf8c6;
text-align: right;
margin-left: auto;
}
.chat-container ::v-deep .bot-message {
background-color: #f0f0f0;
border: 1px solid #eee;
margin-right: auto;
}
.message {
margin-bottom: 10px;
padding: 8px;
border-radius: 4px;
max-width: 80%;
word-wrap: break-word;
}
.user-message {
background-color: #dcf8c6;
text-align: right;
margin-left: auto;
}
.bot-message {
background-color: #f0f0f0;
border: 1px solid #eee;
margin-right: auto;
}
.input-area {
display: flex;
gap: 10px;
}
input, select, button {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
input {
flex-grow: 1;
}
.loading {
color: #666;
font-style: italic;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/PersonalAssistant.vue
|
Vue
|
unknown
| 16,873
|
<template>
<div class="register-container">
<div style="width: 400px; margin: 80px auto; position: absolute; left: 35%;">
<div style="color: black; font-size: 40px; text-align: center; padding: 30px 0">注 册</div>
<el-form ref="form" :model="form" :rules="rules" size="large">
<el-form-item prop="identity">
<div style="display: flex; align-items: center; color: grey; font-size: 14px; font-weight: 500;">
请选择您的身份:
<el-radio v-model="form.identity" label="tenant">租客</el-radio>
<el-radio v-model="form.identity" label="landlord">房东</el-radio>
<el-radio v-model="form.identity" label="admin">管理员</el-radio>
</div>
</el-form-item>
<el-form-item prop="username">
<el-input v-model="form.username" clearable prefix-icon="avatar" placeholder="用户名"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input v-model="form.password" clearable prefix-icon="lock" show-password placeholder="密码"></el-input>
</el-form-item>
<el-form-item prop="phone">
<el-input v-model="form.phone" clearable prefix-icon="phone" placeholder="电话号码"></el-input>
</el-form-item>
<el-form-item prop="email">
<el-input v-model="form.email" clearable prefix-icon="message" placeholder="邮箱"></el-input>
</el-form-item>
<el-form-item>
<el-button :disabled="!disabled" style="width: 30%; margin-left: auto; font-size: 15px;" type="primary" @click="register">注册/登录</el-button>
</el-form-item>
</el-form>
</div>
</div>
<div class="footer">
©Copyright 2025 UPC, Edu.
</div>
</template>
<script src="@/assets/js/Register.js"></script>
<style scoped>
.register-container {
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: linear-gradient(
135deg,
hsl(170deg, 80%, 70%),
hsl(190deg, 80%, 70%),
hsl(250deg, 80%, 70%),
hsl(320deg, 80%, 70%),
hsl(320deg, 80%, 70%),
hsl(250deg, 80%, 70%),
hsl(190deg, 80%, 70%),
hsl(190deg, 80%, 70%),
hsl(170deg, 80%, 70%)
);
background-size: 600%;
animation: animation 15s linear infinite;
}
@keyframes animation {
0% {
background-position: 0 0;
}
100% {
background-position: 100% 100%;
}
}
.footer {
left: 0;
bottom: 0;
color: #fff;
width: 100%;
position: absolute;
text-align: center;
line-height: 30px;
padding-bottom: 10px;
text-shadow: #000 0.1em 0.1em 0.1em;
font-size: 14px;
}
.footer a,
.footer span {
color: #fff;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/Register.vue
|
Vue
|
unknown
| 3,090
|
<template>
<div class="common-layout">
<el-container>
<!-- 头部 -->
<el-header style="background-color: #1b4989; color: white; display: flex; align-items: center; justify-content: space-between; padding: 0 20px;">
<!-- 面包屑导航 -->
<el-breadcrumb separator-icon="ArrowRight" style="margin: 10px">
<el-breadcrumb-item :to="{ path: '/TenantHome' }" style="color: white;">首页</el-breadcrumb-item>
<el-breadcrumb-item style="color: white;">查看房源</el-breadcrumb-item>
</el-breadcrumb>
<!-- 搜索功能 -->
<div style="display: flex; align-items: right; gap: 10px;">
<el-input v-model="search" placeholder="请输入搜索内容" style="width: 300px;"/>
<el-button @click="SearchHouse" type="primary" plain icon="Search">搜索</el-button>
<el-button @click="ResetSearch" type="info" plain icon="Refresh">重置</el-button>
</div>
<el-button @click="SignOut" type="info" size="medium" plain icon="Avatar">退出登录</el-button>
</el-header>
<!-- 主要内容 -->
<el-main>
<div style="display: flex; font-weight: bold; font-family: Microsoft YaHei; font-size: 20px; margin-top: 0%;">
房源列表
<div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
</div>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<div v-if="displayData.length === 0" style="position: relative; left: 47.5%; margin-top: 8%;">
暂无数据
</div>
<!-- 将v-for移到el-card上,确保每个数据项都有独立的卡片 -->
<el-card
v-else
v-for="item in displayData"
:key="item.houseId"
shadow="hover"
style="margin-top: 2%; margin-left: 5%; width: calc(90% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease;"
>
<div class="common-layout">
<el-container>
<el-aside width="200px">
<el-image :src="item.imageUrl" fit="fill" style="width: 100%; height: 100%"></el-image>
</el-aside>
<el-container>
<el-header style="position: relative; padding-right: 80px;">
<router-link
:to="{ name: 'HouseDisplay', query: { houseId: item.houseId } }"
style="font-family: Microsoft YaHei; display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
>
{{ item.title }}:{{ item.address }}
</router-link>
<el-tag
:type="getStatusTagType(item.status)"
effect="dark"
size="medium"
style="width: auto; height: 30px; position: absolute; right: 0; top: 20%; transform: translateY(-40%); font-weight: bolder ; font-size: 14.5px; white-space: nowrap;"
>
{{ getStatusLabel(item.status) }}
</el-tag>
</el-header>
<el-main style="margin-top: -5%;">
{{ item.description }}
</el-main>
</el-container>
</el-container>
</div>
</el-card>
</div>
</el-main>
</el-container>
</div>
</template>
<script src="@/assets/js/SelectHouse.js"></script>
<!--注意######样式的优先级受Element plus影响,部分 Element 组件内部使用了自己定义的颜色值,而不是继承父级,需要显示设置####-->
<style scoped>
@import '../assets/css/AdminHome.css';
:deep(.el-breadcrumb__item .el-breadcrumb__inner)
{
color
: white !important;
}
.el-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: rgba(0, 0, 0, 0.2);
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/SelectHouse.vue
|
Vue
|
unknown
| 4,185
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好,用户 {{ username }} !欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/TenantHome">首页</el-menu-item>
<el-menu-item index="/TenantFavorite">我的收藏</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/tenantApplication">我的申请</el-menu-item>
<el-menu-item index="/TenantRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/SelectHouse">查看房源</el-menu-item>
<el-menu-item index="/VectorDatabase">向量数据库</el-menu-item>
<el-menu-item index="/PersonalAssistant">RAG问答助手</el-menu-item>
<el-menu-item index="/GraphRAGAssistant">GraphRAG问答助手</el-menu-item>
<el-menu-item index="/TenantSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-main>
<div style="display: flex; font-weight: bold; font-family: Microsoft YaHei; font-size: 20px; margin-top: 0%;">
我的申请列表
<div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
</div>
<div style="display: flex; align-items: center; justify-content: space-between; margin-top: 1%;">
<div style="display: flex; align-items: center; gap: 50px;">
<el-switch v-model="approved" inactive-text="已通过"></el-switch>
<el-switch v-model="pending" inactive-text="待审核"></el-switch>
<el-switch v-model="rejected" inactive-text="已拒绝"></el-switch>
</div>
</div>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<el-card shadow="hover" style="margin-top: 2%; width: calc(100% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2); transition: all 0.3s ease; ">
<el-table :data="filteredData" style="width: 100%" border>
<el-table-column label="房源列表" header-align="center">
<template #default="{ row }">
<div class="common-layout">
<el-container>
<el-aside width="200px">
<el-image :src="houseMap.get(row.houseId)?.image_url" fit="fill" style="width: 100%; height: 100%"></el-image>
</el-aside>
<el-tag
style="position: absolute; top: 10px; right: 10px;">
{{ getTypeLabel(row.type) }}
</el-tag>
<el-container>
<span style="font-size: 15px; color: black; white-space: nowrap; margin-left: 16npmpx;">申请时间:{{ row.formattedTime }}</span>
<el-tag
:type="getStatusTagType(row.status)"
effect="dark"
style="position: absolute; bottom: 10px; right: 10px;"
>
{{ getStatusLabel(row.status) }}
</el-tag>
<el-header>
<router-link :to="{ name: 'TenantApplicationHouseDisplay', query: { houseId: row.houseId } }" style="font-family: Microsoft YaHei;">
{{ houseMap.get(row.houseId)?.title }}:{{ houseMap.get(row.houseId)?.address }}
</router-link>
</el-header>
<el-main style="margin-top: -5%;">
{{ houseMap.get(row.houseId)?.description }}
<el-tag
:type="getStatusTagType(row.status)"
effect="dark"
style="position: absolute; bottom: 10px; right: 10px;"
>
{{ getStatusLabel(row.status) }}
</el-tag>
</el-main>
</el-container>
</el-container>
</div>
</template>
</el-table-column>
<el-table-column label="操作" width="150" header-align="center">
<template #default="scope">
<div style="display: flex; flex-direction: column; align-items: baseline; gap: 8px;">
<!-- 待审核状态:加快审批 -->
<template v-if="scope.row.status === 'pending'">
<el-button
icon="Timer"
type="warning"
@click="handleSpeedUp(scope.row)"
size="small"
>
加快审批
</el-button>
</template>
<!-- 已拒绝状态:删除申请 -->
<template v-if="scope.row.status === 'rejected'">
<el-popconfirm
title="确认删除该申请?删除后不可恢复"
@confirm="handleDelete(scope.row)"
>
<template #reference>
<el-button
icon="Delete"
type="danger"
size="small"
>
删除申请
</el-button>
</template>
</el-popconfirm>
</template>
<!-- 已通过状态:退房申请 -->
<template v-if="scope.row.status === 'approved'">
<el-popconfirm
title="确认提交退房申请?"
@confirm="handleCheckOut(scope.row)"
>
<template #reference>
<el-button
icon="HomeFilled"
type="info"
size="small"
>
退房申请
</el-button>
</template>
</el-popconfirm>
</template>
</div>
</template>
</el-table-column>
</el-table>
</el-card>
</div>
</el-main>
</el-container>
</div>
</div>
</template>
<script src="@/assets/js/TenantApplication.js"></script>
<style scoped>
/* 样式保持不变 */
.background {
background-color: whitesmoke;
height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.line{
background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x;
height: 0.4rem;
flex: 1;
background-size: auto;
margin: 0.16rem;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/TenantApplication.vue
|
Vue
|
unknown
| 10,590
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/tenantHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item :to="{ path: '/tenantApplication' }">我的申请</el-breadcrumb-item>
<el-breadcrumb-item>房源信息展示</el-breadcrumb-item>
<router-link to="/TenantApplication" style="position: relative; right: -72%;">
<el-button type="primary" style="width: 55px; height: 33px; font-size: 14px; font-family: 'Segoe UI'; border-radius: 10px;">返回</el-button>
</router-link>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div class="common-layout">
<el-container>
<el-header>
<h1 style="font-size: 26px; font-weight: bold; text-align: center; ">{{ Data.title }}</h1>
<el-tag
:type="getStatusTagType(Data.status)"
size="large" style="position: relative; left: 94%; top: -57%; font-weight: bold; font-size: 14px;">
{{ getStatusLabel(Data.status) }}
</el-tag>
</el-header>
<el-container>
<el-aside width="500px">
<el-image :src="Data.imageUrl" fit="fill" style="width: 100%; height: 100%; border-radius: 10px;"></el-image>
</el-aside>
<el-main>
<el-col :gutter="20" style="margin-top: -20px;">
<el-row :span="8"><p><strong>住房名称:</strong>{{ Data.title }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房编号:</strong>{{ Data.houseId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>房东编号:</strong>{{ Data.landlordId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>所在地区:</strong>{{ Data.area }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>地址:</strong>{{ Data.address }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房描述:</strong>{{ Data.description }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房面积:</strong>{{ Data.size }} 平方米</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>户型:</strong>{{ Data.rooms }} 居室</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>楼层:</strong>{{ Data.floor }} 层</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>租金:</strong>{{ Data.price }} 元/月</p></el-row>
<el-row style="display: flex; justify-content: flex-end; margin-top: 5px;">
<el-button
:icon="isFavorited ? 'StarFilled' : 'Star'"
circle
:type="isFavorited ? 'warning' : 'default'"
size="large"
@click="handleFavorite"
/>
</el-row>
<div style="display: flex; justify-content: flex-end; margin-top: 15px;">
<button style="padding: 8px 16px; background-color: #409EFF; color: white; border: none; border-radius: 4px; font-size: 14px; cursor: pointer;"
@click="subapplication">
申请租房
</button>
</div>
</el-col>
</el-main>
</el-container>
<!-- 评论区 -->
<el-main style="margin-top: 20px;">
<div style="display: flex; align-items: center; margin-bottom: 15px;">
<h2 style="font-size: 20px; font-weight: bold;">用户评论 ({{ commentCount }})</h2>
<div class="line" style="margin-left: 1.5%; flex: 1; height: 1px; background-color: #eee;"></div>
</div>
<!-- 评论列表(评论数>0时显示) -->
<div v-if="comments.length > 0">
<div
v-for="comment in comments"
:key="comment.id"
style="margin-bottom: 15px; padding: 15px; border: 1px solid #ebeef5; border-radius: 4px;"
>
<!-- 评论头部:用户信息+评分+时间 -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<div>
<span style="font-weight: 600; color: #303133;">{{ userMap[comment.tenantId] || '匿名用户' }}</span>
<el-rate
v-model="comment.rating"
disabled
:colors="['#99A9BF', '#F7BA1E', '#FF9900']"
style="margin-left: 10px;"
/>
</div>
<span style="font-size: 12px; color: #909399;">{{ formatDate(comment.commentTime) }}</span>
</div>
<!-- 评论内容 -->
<div style="color: #606266; line-height: 1.6;">{{ comment.content }}</div>
</div>
</div>
<!-- 暂无评论(评论数=0时显示) -->
<div v-else style="text-align: center; padding: 50px 0; color: #909399;">
暂无评论,快来发表第一条评论吧!
</div>
<!-- 评论输入框 -->
<div style="margin-bottom: 30px; padding: 20px; background-color: #f5f7fa; border-radius: 8px;">
<!-- 五星评分 -->
<div class="demo-rate-block">
<span class="demonstration" style="font-size: 20px; font-weight: bold;">评分:</span>
<el-rate v-model="rating" :colors="colors" />
</div>
<textarea
v-model="commentContent"
style="width: 100%; height: 120px; padding: 12px; border: 1px solid #dcdfe6; border-radius: 4px; resize: none; font-size: 14px; color: #606266; outline: none;"
placeholder="分享你的想法..."></textarea>
<div style="display: flex; justify-content: flex-end; margin-top: 15px;">
<button style="padding: 8px 16px; background-color: #409eff; color: white; border: none; border-radius: 4px; font-size: 14px; cursor: pointer;"
@click="subComment">
发布评论
</button>
</div>
</div>
</el-main>
</el-container>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/TenantApplicationHouseDisplay.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/TenantApplicationHouseDisplay.vue
|
Vue
|
unknown
| 6,692
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好!用户 {{ username }} 欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/TenantHome">首页</el-menu-item>
<el-menu-item index="/TenantFavorite">我的收藏</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/TenantApplication">我的申请</el-menu-item>
<el-menu-item index="/TenantRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/SelectHouse">查看房源</el-menu-item>
<el-menu-item index="/VectorDatabase">向量数据库</el-menu-item>
<el-menu-item index="/PersonalAssistant">RAG问答助手</el-menu-item>
<el-menu-item index="/GraphRAGAssistant">GraphRAG问答助手</el-menu-item>
<el-menu-item index="/TenantSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-main>
<div style="display: flex; font-weight: bold; font-family: Microsoft YaHei; font-size: 20px; margin-top: 0%;">
收藏列表
<div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
</div>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<div v-if="total === 0" style="position: relative; left: 47.5%; margin-top: 8%;">
暂无数据
</div>
<el-card
v-else
v-for="item in displayData"
:key="item.houseId"
shadow="hover"
style="margin-top: 2%; margin-left: 5%; width: calc(90% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease;"
>
<div class="common-layout">
<el-container>
<el-aside width="200px">
<el-image :src="item.imageUrl" fit="fill" style="width: 100%; height: 100%"></el-image>
</el-aside>
<el-container>
<el-header style="position: relative; padding-right: 80px;">
<router-link
:to="{ name: 'FavoriteHouseDisplay', query: { houseId: item.houseId } }"
style="font-family: Microsoft YaHei;"
>
{{ item.title }}:{{ item.address }}
</router-link>
<el-tag
:type="getStatusTagType(item.status)"
effect="dark"
size="medium"
style="width: auto; height: 30px; position: absolute; right: 0; top: 20%; transform: translateY(-40%); font-weight: bolder ; font-size: 14.5px; white-space: nowrap;"
>
{{ getStatusLabel(item.status) }}
</el-tag>
</el-header>
<el-main style="margin-top: -5%;">
{{ item.description }}
</el-main>
</el-container>
</el-container>
</div>
</el-card>
</div>
</el-main>
</el-container>
</div>
</div>
</template>
<script src="@/assets/js/TenantFavorite.js"></script>
<style scoped>
.background {
background-color: whitesmoke;
min-height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
min-height: 7vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.line{
background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x;
height: 0.4rem;
flex: 1;
background-size: auto;
margin: 0.16rem;
}
.el-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: rgba(0, 0, 0, 0.2);
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/TenantFavorite.vue
|
Vue
|
unknown
| 6,454
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好!用户 {{ username }} 欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/TenantHome">首页</el-menu-item>
<el-menu-item index="/TenantFavorite">我的收藏</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/tenantApplication">我的申请</el-menu-item>
<el-menu-item index="/TenantRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/SelectHouse">查看房源</el-menu-item>
<el-menu-item index="/VectorDatabase">向量数据库</el-menu-item>
<el-menu-item index="/PersonalAssistant">RAG问答助手</el-menu-item>
<el-menu-item index="/GraphRAGAssistant">GraphRAG问答助手</el-menu-item>
<el-menu-item index="/TenantSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-header class="sub_sub_header_background">
<div class="block text-center">
<el-carousel :interval="4000" type="card" height="300px">
<el-carousel-item v-for="(image, index) in images" :key="index">
<img :src="image.src" :alt="image.alt" style="width: 160%; height: 100%; object-fit: fill;" />
</el-carousel-item>
</el-carousel>
</div>
</el-header>
<el-main>
<div class="font" style="font-weight: bold; font-family: Microsoft YaHei; font-size: 20px; margin-top: 0%;">
精选<font>房源</font>
<router-link to="/SelectHouse" style="position: relative; left: 87%; font-size: 14px">查看更多</router-link>
</div>
<div class="line"></div>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<div v-if="total === 0" style="position: relative; left: 47.5%; margin-top: 8%;">
暂无数据
</div>
<!-- 将v-for移到el-card上,确保每个数据项都有独立的卡片 -->
<div v-else v-for="item in firstSixData" :key="item.houseId">
<el-card shadow="hover" style="margin-top: 1%;margin-left: 5%; width: calc(90% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; ">
<div class="common-layout">
<el-container>
<el-aside width="200px">
<el-image :src="item.imageUrl" fit="fill" style="width: 100%; height: 100%"></el-image>
</el-aside>
<el-container>
<el-header style="position: relative; padding-right: 80px;">
<router-link
:to="{ name: 'HomeDisplay', query: { houseId: item.houseId } }"
style="font-family: Microsoft YaHei; display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
>
{{ item.title }}:{{ item.address }}
</router-link>
<el-tag
:type="getStatusTagType(item.status)"
effect="dark"
size="medium"
style="width: auto; height: 30px; position: absolute; right: 0; top: 20%; transform: translateY(-40%); font-weight: bolder ; font-size: 14.5px; white-space: nowrap;"
>
{{ getStatusLabel(item.status) }}
</el-tag>
</el-header>
<el-main style="margin-top: -5%;">
{{ item.description }}
</el-main>
</el-container>
</el-container>
</div>
</el-card>
</div>
</div>
</el-main>
</el-container>
</div>
</div>
</template>
<script src="@/assets/js/TenantHome.js">
</script>
<style scoped>
.background {
background-color: whitesmoke;
min-height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.sub_sub_header_background {
background-color: #ddebff;
height: 43.1vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.font font {
color: #0465C4;
}
.line{
background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x;
height: 0.4rem;
flex: 1;
background-size: auto;
margin: 0.16rem;
}
.el-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: rgba(0, 0, 0, 0.2);
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/TenantHome.vue
|
Vue
|
unknown
| 7,301
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/adminHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>用户信息管理</el-breadcrumb-item>
<el-breadcrumb-item>租客信息</el-breadcrumb-item>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div style="color: black; font-size: 20px;font-weight: bolder; text-align: center;">租客信息</div>
<div>
<div style="margin: 40px 0">
<div style="margin: 10px 0">
<el-input v-model="search"
@input="filterData"
clearable
placeholder="请输入租客ID号"
prefix-icon="Search"
style="width: 20%"/>
<el-button icon="Search" style="margin-left: 5px" type="primary" @click="filterData"></el-button>
<el-button icon="refresh-left" style="margin-left: 10px" type="default" @click="reset"></el-button>
<div style="float: right">
<el-tooltip content="添加" placement="top">
<el-button icon="plus" style="width: 50px" type="primary" @click="add"></el-button>
</el-tooltip>
</div>
</div>
</div>
<!--表格-->
<el-table v-loading="loading" :data="tableData" border max-height="705" style="width: 100%">
<el-table-column label="租客ID" prop="tenantId"/>
<el-table-column label="用户名" prop="username" sortable/>
<el-table-column label="密码" prop="password" />
<el-table-column label="电话号码" prop="phone"/>
<el-table-column :show-overflow-tooltip="true" label="邮箱" prop="email"/>
<el-table-column label="操作" width="130px">
<template #default="scope">
<el-space direction="vertical" alignment="center" style="margin-left: 13%; margin-top: 5%">
<el-button icon="Edit" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
<el-popconfirm title="确认删除?" @confirm="handleDelete(scope.row.tenantId)">
<template #reference>
<el-button icon="Delete" type="danger">删除</el-button>
</template>
</el-popconfirm>
</el-space>
</template>
</el-table-column>
</el-table>
<!--分页-->
<div style="margin: 40px 0">
<el-pagination
v-model:currentPage="currentPage"
:page-size="pageSize"
:page-sizes="[5, 10, 15]"
:total="total"
layout="total, sizes, prev, pager, next, jumper"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"></el-pagination>
</div>
<div>
<!--弹窗-->
<el-dialog v-model="dialogVisible" title="添加租客信息" width="30%" @close="cancel">
<el-form ref="form" :model="form" :rules="rules" label-width="120px">
<!-- <el-form-item label="租客ID" prop="tenantId" v-if="!judgeAddOrEdit">
<el-input v-model="form.tenantId" :disabled="judgeAddOrEdit" style="width: 80%"></el-input>
</el-form-item> -->
<el-form-item label="用户名" prop="username">
<el-input v-model="form.username" :disabled="false" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="form.password" :disabled="false" :show-password="showpassword" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="电话号码" prop="phone">
<el-input v-model.number="form.phone" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="邮箱地址" prop="email">
<el-input v-model="form.email" style="width: 80%"></el-input>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="cancel">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</span>
</template>
</el-dialog>
</div>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/TenantInfo.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/TenantInfo.vue
|
Vue
|
unknown
| 4,584
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好,用户 {{ username }} !欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/TenantHome">首页</el-menu-item>
<el-menu-item index="/TenantFavorite">我的收藏</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/tenantApplication">我的申请</el-menu-item>
<el-menu-item index="/TenantRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/SelectHouse">查看房源</el-menu-item>
<el-menu-item index="/VectorDatabase">向量数据库</el-menu-item>
<el-menu-item index="/PersonalAssistant">RAG问答助手</el-menu-item>
<el-menu-item index="/GraphRAGAssistant">GraphRAG问答助手</el-menu-item>
<el-menu-item index="/TenantSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-main>
<div style="display: flex; font-weight: bold; font-family: Microsoft YaHei; font-size: 20px; margin-top: 0%;">
我的交易记录
<div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
</div>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<el-card shadow="hover" style="margin-top: 2%; width: calc(100% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2); transition: all 0.3s ease;">
<el-table v-loading="loading" :data="paginatedTransactionData" border max-height="705" style="width: 100%">
<el-table-column label="交易单号" prop="recordId" />
<el-table-column label="房屋编号" prop="houseId" />
<el-table-column label="房屋名称" prop="houseId" :formatter="(row) => getHouseTitle(row.houseId)" />
<el-table-column label="房东编号" prop="houseId" :formatter="(row) => getLandlordId(row.houseId)" />
<el-table-column label="房东用户名" prop="houseId" :formatter="(row) => getLandlordUsername(row.houseId)" />
<el-table-column label="房东电话号码" prop="houseId" :formatter="(row) => getLandlordPhone(row.houseId)" />
<el-table-column label="房东邮箱" prop="houseId" :formatter="(row) => getLandlordEmail(row.houseId)" />
<el-table-column label="交易时间" prop="recordTime" :formatter="(row) => formatTime(row.recordTime)"/>
</el-table>
</el-card>
</div>
<div style="margin: 30px 0;">
<el-pagination
v-model:currentPage="currentPage"
:page-size="pageSize"
:page-sizes="[5, 10, 15]"
:total="transaction_total"
layout="total, sizes, prev, pager, next, jumper"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"></el-pagination>
</div>
</el-main>
</el-container>
</div>
</div>
</template>
<script src="@/assets/js/TenantRecord.js"></script>
<style scoped>
.background {
background-color: whitesmoke;
height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.line{
background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x;
height: 0.4rem;
flex: 1;
background-size: auto;
margin: 0.16rem;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/TenantRecord.vue
|
Vue
|
unknown
| 5,867
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好,用户 {{ username }} !欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/tenantHome">首页</el-menu-item>
<el-menu-item index="/TenantFavorite">我的收藏</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/TenantApplication">我的申请</el-menu-item>
<el-menu-item index="/TenantRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/SelectHouse">查看房源</el-menu-item>
<el-menu-item index="/VectorDatabase">向量数据库</el-menu-item>
<el-menu-item index="/PersonalAssistant">RAG问答助手</el-menu-item>
<el-menu-item index="/GraphRAGAssistant">GraphRAG问答助手</el-menu-item>
<el-menu-item index="/TenantSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-main>
<!-- 卡片容器 -->
<el-card id="personal-info-card" style="margin: 15px; min-height: calc(100vh - 111px);">
<div style="display: flex; justify-content: center;">
<div style="width: 600px; margin-left: 30px; position: relative">
<!-- 用户信息展示 -->
<div style="margin: 20px 0;">
<h3 class="personal-info-title" style="margin-bottom: 30px; color: #333;font-size: 30px;">👤 个人信息</h3>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<!-- 用户ID -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-user" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>用户ID</strong>
<span style="margin-left: 10px; display: block;">{{ tenantId }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<User />
</el-icon>
</div>
</div>
</el-card>
<!-- 用户名 -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-document" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>用户名</strong>
<span style="margin-left: 10px; display: block;">{{ username }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<UserFilled />
</el-icon>
</div>
</div>
</el-card>
<!-- 手机号 -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-phone" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>手机号</strong>
<span style="margin-left: 10px; display: block;">{{ phone }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<Iphone />
</el-icon>
</div>
</div>
</el-card>
<!-- 邮箱 -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-message" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>邮箱</strong>
<span style="margin-left: 10px; display: block;">{{ email }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<Message />
</el-icon>
</div>
</div>
</el-card>
</div>
</div>
<!-- 修改按钮 -->
<el-tooltip content="修改信息" placement="bottom">
<el-button
icon="Edit"
size="large"
type="primary"
style="
margin-top: 30px;
width: 80px;
transition: transform 0.2s ease;
"
@click="Edit"
@mouseenter.native="e => e.target.style.transform = 'scale(1.1)'"
@mouseleave.native="e => e.target.style.transform = 'scale(1)'"
>
</el-button>
</el-tooltip>
</div>
</div>
</el-card>
<!-- 修改信息弹窗 -->
<el-dialog v-model="dialogVisible" title="操作" width="30%" @close="resetForm">
<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
<el-form-item label="用户ID" prop="tenantId">
<el-input v-model="form.tenantId" disabled style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="用户名" prop="username">
<el-input v-model="form.username" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="form.password" :disabled="disabled" show-password style="width: 80%"></el-input>
<el-tooltip content="修改密码" placement="right">
<el-icon size="large" style="margin-left: 5px; cursor: pointer" @click="EditPass">
<edit />
</el-icon>
</el-tooltip>
</el-form-item>
<!-- <el-form-item label="确认密码" prop="checkPass" :style="display">
<el-input v-model="form.checkPass" show-password style="width: 80%"></el-input>
</el-form-item> -->
<el-form-item label="手机号" prop="phone">
<el-input v-model.number="form.phone" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="邮箱地址" prop="email">
<el-input v-model="form.email" style="width: 80%"></el-input>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="cancel">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</span>
</template>
</el-dialog>
</el-main>
</el-container>
</div>
</div>
</template>
<script>
import request from "@/axios/request";
const {ElMessage} = require('element-plus');
export default {
data() {
return {
loading: true,
tenantId: '',
username: '',
password: '',
phone: '',
email: '',
dialogVisible: false,
form: {
tenantId: '',
username: '',
password: '',
checkPass: '',
phone: '',
email: ''
},
rules: {
// 验证规则(可根据实际需求扩展)
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 6, message: '密码至少6位', trigger: 'blur' }
],
checkPass: [
{ validator: (rule, value, callback) => {
if (value !== this.form.password) {
callback(new Error('两次输入密码不一致'));
} else {
callback();
}
}, trigger: 'blur' }
],
phone: [
{ required: true, message: '请输入手机号', trigger: 'blur' },
{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
],
email: [
{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
{ type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
]
},
display: { display: 'none' },
disabled: true
};
},
mounted() {
this.fetchUserInfo();
},
methods: {
async fetchUserInfo() {
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
const tenantId = token.tenantId;
const res = await request.get(`/tenant/findById/${tenantId}`);
if (res.code === 200) {
token=res.data;
} else {
ElMessage.error("获取用户信息失败");
}
console.log(token);
if(!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.tenantId = token.tenantId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
console.log(token);
},
Edit() {
this.form.tenantId = this.tenantId;
this.form.username = this.username;
this.form.password = this.password;
this.form.phone = this.phone;
this.form.email = this.email;
this.dialogVisible = true;
},
cancel() {
this.resetForm();
this.dialogVisible = false;
},
save() {
console.log('提交数据:', this.form);
fetch('/tenant/updateById', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.form)
})
.then(res => res.json())
.then(data => {
if (data.success) {
this.fetchUserInfo(); // 刷新页面数据
} else {
alert('更新失败,请重试');
}
})
.catch(err => {
console.error('请求出错:', err);
});
this.resetForm();
this.dialogVisible = false;
},
EditPass() {
this.disabled = false;
this.display.display = 'block';
},
resetForm() {
this.form.username = this.username;
this.form.password = this.password;
this.form.checkPass = '';
this.form.phone = this.phone;
this.form.email = this.email;
this.disabled = true;
this.display.display = 'none';
if (this.$refs.formRef && this.$refs.formRef.resetFields) {
this.$refs.formRef.resetFields();
}
},
SignOut() {
sessionStorage.clear();
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({ path: '/Login' });
},
}
};
</script>
<style scoped>
.background {
background-color: whitesmoke;
height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.el-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: #409EFF;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/TenantSelfInfo.vue
|
Vue
|
unknown
| 15,739
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好,用户 {{ username }} !欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/tenantHome">首页</el-menu-item>
<el-menu-item index="/TenantFavorite">我的收藏</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/TenantApplication">我的申请</el-menu-item>
<el-menu-item index="/TenantRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/SelectHouse">查看房源</el-menu-item>
<el-menu-item index="/VectorDatabase">向量数据库</el-menu-item>
<el-menu-item index="/PersonalAssistant">RAG问答助手</el-menu-item>
<el-menu-item index="/GraphRAGAssistant">GraphRAG问答助手</el-menu-item>
<el-menu-item index="/TenantSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-main>
<el-card id="personal-info-card" style="margin: 5px; min-height: calc(100vh - 110px);">
<h1 style="text-align: center;">向量数据库</h1>
<h2 style="text-align: center;">帮助您一键获取最全房源信息</h2>
<div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
<div style="display: flex; gap: 20px; margin: 20px 0; align-items: center;">
<h4 style="position: relative; left: 2%;">房源</h4>
<el-select
v-model="selectedHouse"
filterable
remote
reserve-keyword
placeholder="请输入房源名称"
:remote-method="searchHouses"
:loading="loadingHouses"
style="position: relative; left: 1%; width: 25%;"
:filter-method="searchHouses"
@focus="loadAllHouses">
<el-option
v-for="item in houseOptions"
:key="item.title"
:label="item.title"
:value="item.title">
</el-option>
</el-select>
<h4 style="position: relative; left: 1%;">分块方式</h4>
<el-select
v-model="chunkMethod"
placeholder="请选择分块方式"
style="position: relative; left: 0%; width: 25%;">
<el-option label="按大小分块" value="recursive"></el-option>
<el-option label="按语义分块" value="semantic"></el-option>
</el-select>
<h4 style="position: relative; left: 0%;">查看目标</h4>
<el-select
v-model="checkMode"
placeholder="请选择查看目标"
style="position: relative; left: -1%; width: 25%;">
<el-option label="查看特定文档的分块内容" value="chunk"></el-option>
<el-option label="查看所有文档摘要" value="summary"></el-option>
<el-option label="查看数据库文件结构" value="structure"></el-option>
</el-select>
</div>
<div style="display: flex;">
<h3 style="position: relative; left: 2%;">向量数据库内容展示</h3>
<div class="line" style="margin-left: 4%;; margin-right: 4%; margin-top: 1%;"></div>
<!-- 保存按钮 -->
<el-button
type="primary"
icon="Download"
circle
@click="saveToFile"
:loading="saving"
title="保存"
style="position: relative; right: 0%">
</el-button>
</div>
<!-- 展示向量数据库中的内容 -->
<div style="margin: 20px; padding: 15px; border: 1px solid #ebeef5; border-radius: 4px; min-height: 300px;">
<pre v-if="summaryData">{{ summaryData }}</pre>
<pre v-else-if="structureData">{{ structureData }}</pre>
<pre v-else-if="chunkData">{{ chunkData }}</pre>
<div v-else style="color: #909399; text-align: center; line-height: 300px;">
请选择查看目标、房源名称与分块方式以获取数据
</div>
</div>
</el-card>
</el-main>
</el-container>
</div>
</div>
</template>
<script>
import request from "@/axios/request";
import request2 from "@/axios/request2";
import request3 from "@/axios/request3";
import request4 from "@/axios/request4";
import { ElMessage } from 'element-plus';
export default {
data() {
return {
loading: true,
loadingHouses: false,
saving: false,
tenantId: '',
username: '',
password: '',
phone: '',
email: '',
selectedHouse: '',
houseOptions: [],
allHouses: [],
chunkMethod: '',
checkMode: '',
chunkCheckTimer: null,
summaryData: '',
structureData: '',
chunkData: ''
};
},
mounted() {
this.fetchUserInfo();
this.loadAllHouses();
this.loadVectorDatabase();
},
beforeUnmount() {
if(this.chunkCheckTimer){
clearInterval(this.chunkCheckTimer);
}
},
methods: {
async loadAllHouses() {
this.loadingHouses = true;
try {
const res = await request.get("/house/findAll");
if (res.code === 200) {
this.allHouses = res.data || [];
// 初始化时显示所有房源
this.houseOptions = this.allHouses.map(item => ({
houseId: item.houseId,
title: item.title
}));
} else {
ElMessage.error(res.msg || "加载房源数据失败");
}
} catch (err) {
console.error("加载房源数据错误:", err);
ElMessage.error("网络错误,请稍后再试");
} finally {
this.loadingHouses = false;
}
},
async loadVectorDatabase() {
this.$watch('checkMode', async (newVal) => {
this.summaryData = '';
this.structureData = '';
this.chunkData = '';
if (newVal === 'summary') {
try {
const res = await request3.get('/vector/summary');
if (res.code === 200) {
console.log('摘要数据:', res.data);
this.summaryData = JSON.stringify(res.data, null, 2);
} else {
ElMessage.error(res.msg || "获取摘要数据失败");
}
} catch (err) {
console.error("获取摘要数据错误:", err);
ElMessage.error("网络错误,请稍后再试");
}
} else if (newVal === 'structure') {
try {
const res = await request3.get('/vector/structure');
if (res.code === 200) {
console.log('结构数据:', res.data);
this.structureData = JSON.stringify(res.data, null, 2);
} else {
ElMessage.error(res.msg || "获取结构数据失败");
}
} catch (err) {
console.error("获取结构数据错误:", err);
ElMessage.error("网络错误,请稍后再试");
}
} else if (newVal === 'chunk') {
this.checkChunkRequirements();
}
});
this.$watch('selectedHouse', () => {
if (this.checkMode === 'chunk') {
this.checkChunkRequirements();
}
});
this.$watch('chunkMethod', () => {
if (this.checkMode === 'chunk') {
this.checkChunkRequirements();
}
});
},
async checkChunkRequirements() {
if (this.chunkCheckTimer) {
clearInterval(this.chunkCheckTimer);
}
const checkAndLoad = async () => {
if (!this.selectedHouse && this.checkMode === 'chunk') {
ElMessage.warning("请选择房源");
return false;
}
if (!this.chunkMethod && this.checkMode === 'chunk') {
ElMessage.warning("请选择分块方式");
return false;
}
try {
const res = await request3.post('/vector/chunk', {
params: {
title: this.selectedHouse,
chunkMethod: this.chunkMethod
}
});
if (res.code === 200) {
console.log('分块内容数据:', res.data);
this.chunkData = JSON.stringify(res.data, null, 2);
if (this.chunkCheckTimer) {
clearInterval(this.chunkCheckTimer);
this.chunkCheckTimer = null;
}
return true;
} else {
ElMessage.error(res.msg || "获取分块内容失败");
return false;
}
} catch (err) {
console.error("获取分块内容错误:", err);
ElMessage.error("网络错误,请稍后再试");
return false;
}
};
const success = await checkAndLoad();
if (!success) {
this.chunkCheckTimer = setInterval(checkAndLoad, 10000);
}
},
async fetchUserInfo() {
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
const tenantId = token.tenantId;
const res = await request.get(`/tenant/findById/${tenantId}`);
if (res.code === 200) {
token=res.data;
} else {
ElMessage.error("获取用户信息失败");
}
console.log(token);
if(!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.tenantId = token.tenantId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
console.log(token);
},
// 搜索房源
searchHouses(query) {
if (!query) {
this.houseOptions = this.allHouses.map(item => ({
houseId: item.houseId,
title: item.title
}));
return;
}
const filteredHouses = this.allHouses.filter(item =>
(item.title).toLowerCase().includes(query.toLowerCase())
);
this.houseOptions = filteredHouses.map(item => ({
houseId: item.houseId,
title: item.title
}));
},
// 保存到文件
async saveToFile() {
if (!this.selectedHouse && this.checkMode === 'chunk') {
ElMessage.warning("请选择房源");
return;
}
if (!this.chunkMethod && this.checkMode === 'chunk') {
ElMessage.warning("请选择分块方式");
return;
}
if (!this.checkMode) {
ElMessage.warning("请选择查看目标");
return;
}
this.saving = true;
try {
const res = await request4.post('/vector/save', {
title: this.selectedHouse,
chunkMethod: this.chunkMethod,
checkMode: this.checkMode
});
if (res.code === 200) {
ElMessage.success("文件保存成功 (保存路径:D:\\\\Edge下载)");
} else {
ElMessage.error(res.msg || "保存失败");
}
} catch (err) {
console.error("保存文件错误:", err);
ElMessage.error("网络错误,请稍后再试");
} finally {
this.saving = false;
}
},
SignOut() {
sessionStorage.clear();
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({ path: '/Login' });
},
}
};
</script>
<style scoped>
.background {
background-color: whitesmoke;
height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.el-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: #409EFF;
}
.line{
background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x;
height: 0.4rem;
flex: 1;
background-size: auto;
margin: 0.16rem;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/VectorDatabase.vue
|
Vue
|
unknown
| 15,167
|
// 跨域配置
module.exports = {
publicPath: './',
devServer: {
// proxy: {
// '/': {
// target: 'http://localhost:8089/main',
// changeOrigin: true,
// pathRewrite: {
// '^/': '/'
// }
// }
// }
}
}
|
2301_79970562/student_union_frontend
|
vue.config.js
|
JavaScript
|
unknown
| 414
|
cmake_minimum_required(VERSION 3.16)
project(No7 VERSION 0.1 LANGUAGES CXX)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets LinguistTools)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets LinguistTools)
set(TS_FILES No7_zh_CN.ts)
set(PROJECT_SOURCES
main.cpp
mainwindow.cpp
mainwindow.h
mainwindow.ui
${TS_FILES}
)
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
qt_add_executable(No7
MANUAL_FINALIZATION
${PROJECT_SOURCES}
img.qrc
loginwindow.h
loginwindow.cpp
loginwindow.ui
addcollegewindow.h
addcollegewindow.cpp
addeventwindow.h
addeventwindow.cpp
addresultwindow.h
addresultwindow.cpp
displayresultswindow.h
displayresultswindow.cpp
displaydatawindow.h
displaydatawindow.cpp
addcollegewindow.ui
addeventwindow.ui
addresultwindow.ui
displayresultswindow.ui
displaydatawindow.ui
)
# Define target properties for Android with Qt 6 as:
# set_property(TARGET No7 APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR
# ${CMAKE_CURRENT_SOURCE_DIR}/android)
# For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation
qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
else()
if(ANDROID)
add_library(No7 SHARED
${PROJECT_SOURCES}
)
# Define properties for Android with Qt 5 after find_package() calls as:
# set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android")
else()
add_executable(No7
${PROJECT_SOURCES}
)
endif()
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
endif()
target_link_libraries(No7 PRIVATE Qt${QT_VERSION_MAJOR}::Widgets)
# Qt for iOS sets MACOSX_BUNDLE_GUI_IDENTIFIER automatically since Qt 6.1.
# If you are developing for iOS or macOS you should consider setting an
# explicit, fixed bundle identifier manually though.
if(${QT_VERSION} VERSION_LESS 6.1.0)
set(BUNDLE_ID_OPTION MACOSX_BUNDLE_GUI_IDENTIFIER com.example.No7)
endif()
set_target_properties(No7 PROPERTIES
${BUNDLE_ID_OPTION}
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
MACOSX_BUNDLE TRUE
WIN32_EXECUTABLE TRUE
)
include(GNUInstallDirs)
install(TARGETS No7
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
if(QT_VERSION_MAJOR EQUAL 6)
qt_finalize_executable(No7)
endif()
|
2301_80164243/program
|
CMakeLists.txt
|
CMake
|
unknown
| 2,880
|
#include "addcollegewindow.h"
#include "ui_addcollegewindow.h"
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
AddCollegeWindow::AddCollegeWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::AddCollegeWindow)
{
ui->setupUi(this);
}
AddCollegeWindow::~AddCollegeWindow()
{
delete ui;
}
void AddCollegeWindow::on_addButton_clicked()
{
QString name = ui->nameLineEdit->text();
if (name.isEmpty()) {
QMessageBox::warning(this, "警告", "学院名称不能为空");
return;
}
// 检查是否有重复数据
QFile file("data.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::warning(this, "错误", "无法打开文件进行读取");
return;
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(" ");
if (fields[0] == "C" && fields[2] == name) {
QMessageBox::warning(this, "警告", "学院名称已存在");
file.close();
return;
}
}
file.close();
emit collegeAdded(name);
QMessageBox::information(this, "提示", "学院添加成功");
this->close();
}
|
2301_80164243/program
|
addcollegewindow.cpp
|
C++
|
unknown
| 1,277
|
#ifndef ADDCOLLEGEWINDOW_H
#define ADDCOLLEGEWINDOW_H
#include <QWidget>
namespace Ui {
class AddCollegeWindow;
}
class AddCollegeWindow : public QWidget
{
Q_OBJECT
public:
explicit AddCollegeWindow(QWidget *parent = nullptr);
~AddCollegeWindow();
signals:
void collegeAdded(const QString &name);
private slots:
void on_addButton_clicked();
private:
Ui::AddCollegeWindow *ui;
};
#endif // ADDCOLLEGEWINDOW_H
|
2301_80164243/program
|
addcollegewindow.h
|
C++
|
unknown
| 468
|
#include "addeventwindow.h"
#include "ui_addeventwindow.h"
#include <QMessageBox>
#include <QDebug>
AddEventWindow::AddEventWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::AddEventWindow)
{
ui->setupUi(this);
// 设置下拉框的items
ui->isTopFiveComboBox->addItem("是");
ui->isTopFiveComboBox->addItem("否");
ui->isMaleComboBox->addItem("是");
ui->isMaleComboBox->addItem("否");
}
AddEventWindow::~AddEventWindow()
{
delete ui;
}
void AddEventWindow::on_addButton_clicked()
{
qDebug() << "Add button clicked";
QString name = ui->nameLineEdit->text();
int isTopFive = ui->isTopFiveComboBox->currentIndex();
bool isMale = ui->isMaleComboBox->currentIndex() == 0;
if (!name.isEmpty()) {
emit eventAdded(name, isTopFive, isMale);
QMessageBox::information(this, "提示", "项目添加成功");
} else {
QMessageBox::warning(this, "警告", "项目名称不能为空");
}
}
|
2301_80164243/program
|
addeventwindow.cpp
|
C++
|
unknown
| 1,012
|
#ifndef ADDEVENTWINDOW_H
#define ADDEVENTWINDOW_H
#include <QWidget>
namespace Ui {
class AddEventWindow;
}
class AddEventWindow : public QWidget
{
Q_OBJECT
public:
explicit AddEventWindow(QWidget *parent = nullptr);
~AddEventWindow();
signals:
void eventAdded(const QString &name, int isTopFive, bool isMale);
private slots:
void on_addButton_clicked();
private:
Ui::AddEventWindow *ui;
};
#endif // ADDEVENTWINDOW_H
|
2301_80164243/program
|
addeventwindow.h
|
C++
|
unknown
| 478
|
#include "addresultwindow.h"
#include "ui_addresultwindow.h"
#include <QMessageBox>
#include <QDebug>
AddResultWindow::AddResultWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::AddResultWindow)
{
ui->setupUi(this);
}
AddResultWindow::~AddResultWindow()
{
delete ui;
}
void AddResultWindow::on_addButton_clicked()
{
qDebug() << "Add button clicked";
int collegeId = ui->collegeIdSpinBox->value();
int eventId = ui->eventIdSpinBox->value();
int rank = ui->rankSpinBox->value();
if (collegeId > 0 && eventId > 0 && rank > 0) {
emit resultAdded(collegeId, eventId, rank);
QMessageBox::information(this, "提示", "比赛结果添加成功");
} else {
QMessageBox::warning(this, "警告", "所有字段都必须填写且大于0");
}
}
|
2301_80164243/program
|
addresultwindow.cpp
|
C++
|
unknown
| 840
|
#ifndef ADDRESULTWINDOW_H
#define ADDRESULTWINDOW_H
#include <QWidget>
namespace Ui {
class AddResultWindow;
}
class AddResultWindow : public QWidget
{
Q_OBJECT
public:
explicit AddResultWindow(QWidget *parent = nullptr);
~AddResultWindow();
signals:
void resultAdded(int collegeId, int eventId, int rank);
private slots:
void on_addButton_clicked();
private:
Ui::AddResultWindow *ui;
};
#endif // ADDRESULTWINDOW_H
|
2301_80164243/program
|
addresultwindow.h
|
C++
|
unknown
| 476
|
#include "displaydatawindow.h"
#include "ui_displaydatawindow.h"
DisplayDataWindow::DisplayDataWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::DisplayDataWindow)
{
ui->setupUi(this);
tableWidget = ui->tableWidget;
tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
tableWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
}
DisplayDataWindow::~DisplayDataWindow()
{
delete ui;
}
void DisplayDataWindow::displayResultsByEvent(const QList<QList<QString>>& data)
{
tableWidget->setRowCount(data.size());
tableWidget->setColumnCount(3); // 设置列数为3
QStringList headers;
headers << "学院/项目" << "学院/项目名称" << "对应编号";
tableWidget->setHorizontalHeaderLabels(headers);
for (int i = 0; i < data.size(); ++i) {
for (int j = 0; j < data[i].size(); ++j) {
tableWidget->setItem(i, j, new QTableWidgetItem(data[i][j]));
}
}
}
void DisplayDataWindow::displayData(const QList<QList<QString>>& data)
{
tableWidget->setRowCount(data.size());
tableWidget->setColumnCount(3); // 设置列数为3
QStringList headers;
headers << "学院/项目" << "学院/项目名称" << "对应编号";
tableWidget->setHorizontalHeaderLabels(headers);
for (int i = 0; i < data.size(); ++i) {
for (int j = 0; j < data[i].size(); ++j) {
tableWidget->setItem(i, j, new QTableWidgetItem(data[i][j]));
}
}
}
|
2301_80164243/program
|
displaydatawindow.cpp
|
C++
|
unknown
| 1,522
|
#ifndef DISPLAYDATAWINDOW_H
#define DISPLAYDATAWINDOW_H
#include <QWidget>
#include <QTableWidget>
namespace Ui {
class DisplayDataWindow;
}
class DisplayDataWindow : public QWidget
{
Q_OBJECT
public:
explicit DisplayDataWindow(QWidget *parent = nullptr);
~DisplayDataWindow();
void displayData(const QList<QList<QString>>& data);
void displayResultsByEvent(const QList<QList<QString>>& data);
private:
Ui::DisplayDataWindow *ui;
QTableWidget *tableWidget;
};
#endif // DISPLAYDATAWINDOW_H
|
2301_80164243/program
|
displaydatawindow.h
|
C++
|
unknown
| 550
|
#include "displayresultswindow.h"
#include "ui_displayresultswindow.h"
DisplayResultsWindow::DisplayResultsWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::DisplayResultsWindow)
{
ui->setupUi(this);
tableWidget = ui->tableWidget;
}
DisplayResultsWindow::~DisplayResultsWindow()
{
delete ui;
}
void DisplayResultsWindow::displayResults(const QList<QList<QString>>& results)
{
tableWidget->setRowCount(results.size());
for (int i = 0; i < results.size(); ++i) {
for (int j = 0; j < results[i].size(); ++j) {
tableWidget->setItem(i, j, new QTableWidgetItem(results[i][j]));
}
}
}
|
2301_80164243/program
|
displayresultswindow.cpp
|
C++
|
unknown
| 670
|
#ifndef DISPLAYRESULTSWINDOW_H
#define DISPLAYRESULTSWINDOW_H
#include <QWidget>
#include <QTableWidget>
namespace Ui {
class DisplayResultsWindow;
}
class DisplayResultsWindow : public QWidget
{
Q_OBJECT
public:
explicit DisplayResultsWindow(QWidget *parent = nullptr);
~DisplayResultsWindow();
void displayResults(const QList<QList<QString>>& results);
private:
Ui::DisplayResultsWindow *ui;
QTableWidget *tableWidget;
};
#endif // DISPLAYRESULTSWINDOW_H
|
2301_80164243/program
|
displayresultswindow.h
|
C++
|
unknown
| 514
|
#include "loginwindow.h"
#include "ui_loginwindow.h"
#include "mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
LoginWindow::LoginWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::LoginWindow)
{
ui->setupUi(this);
}
LoginWindow::~LoginWindow()
{
delete ui;
}
void LoginWindow::on_loginButton_clicked()
{
QString username = ui->usernameLineEdit->text();
QString password = ui->passwordLineEdit->text();
if (validateCredentials(username, password)) {
emit loginSuccess();
this->close();
} else {
QMessageBox::warning(this, "登录失败", "用户名或密码错误");
}
}
void LoginWindow::on_registerButton_clicked()
{
QString username = ui->usernameLineEdit->text();
QString password = ui->passwordLineEdit->text();
saveUserData(username, password);
QMessageBox::information(this, "注册成功", "用户注册成功");
}
bool LoginWindow::validateCredentials(const QString &username, const QString &password)
{
QFile file("user_data.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(" ");
if (fields.size() == 2 && fields[0] == username && fields[1] == password) {
return true;
}
}
return false;
}
void LoginWindow::saveUserData(const QString &username, const QString &password)
{
QFile file("user_data.txt");
if (!file.open(QIODevice::Append | QIODevice::Text))
return;
QTextStream out(&file);
out << username << " " << password << "\n";
}
|
2301_80164243/program
|
loginwindow.cpp
|
C++
|
unknown
| 1,766
|
#ifndef LOGINWINDOW_H
#define LOGINWINDOW_H
#include <QMainWindow>
namespace Ui {
class LoginWindow;
}
class LoginWindow : public QMainWindow
{
Q_OBJECT
public:
explicit LoginWindow(QWidget *parent = nullptr);
~LoginWindow();
signals:
void loginSuccess();
private slots:
void on_loginButton_clicked();
void on_registerButton_clicked();
private:
Ui::LoginWindow *ui;
bool validateCredentials(const QString &username, const QString &password);
void saveUserData(const QString &username, const QString &password);
};
#endif // LOGINWINDOW_H
|
2301_80164243/program
|
loginwindow.h
|
C++
|
unknown
| 615
|
#include "loginwindow.h"
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
LoginWindow loginWindow;
MainWindow mainWindow;
QObject::connect(&loginWindow, &LoginWindow::loginSuccess, [&mainWindow]() {
mainWindow.show();
});
loginWindow.show();
return a.exec();
}
|
2301_80164243/program
|
main.cpp
|
C++
|
unknown
| 379
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QInputDialog>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
, addCollegeWindow(new AddCollegeWindow(this->parentWidget()))
, addEventWindow(new AddEventWindow(this->parentWidget()))
, addResultWindow(new AddResultWindow(this->parentWidget()))
, displayResultsWindow(new DisplayResultsWindow(this->parentWidget()))
, displayDataWindow(new DisplayDataWindow(this->parentWidget()))
{
ui->setupUi(this);
connect(ui->addCollegeButton, &QPushButton::clicked, this, &MainWindow::on_addCollegeButton_clicked);
connect(ui->addEventButton, &QPushButton::clicked, this, &MainWindow::on_addEventButton_clicked);
connect(ui->addResultButton, &QPushButton::clicked, this, &MainWindow::on_addResultButton_clicked);
connect(ui->displayResultsButton, &QPushButton::clicked, this, &MainWindow::on_displayResultsButton_clicked);
connect(ui->displayDataButton, &QPushButton::clicked, this, &MainWindow::on_displayDataButton_clicked);
connect(ui->modifyCollegeButton, &QPushButton::clicked, this, &MainWindow::on_modifyCollegeButton_clicked);
connect(ui->modifyEventButton, &QPushButton::clicked, this, &MainWindow::on_modifyEventButton_clicked);
connect(ui->deleteResultButton, &QPushButton::clicked, this, &MainWindow::on_deleteResultButton_clicked);
connect(addCollegeWindow, &AddCollegeWindow::collegeAdded, this, &MainWindow::handleCollegeAdded);
connect(addEventWindow, &AddEventWindow::eventAdded, this, &MainWindow::handleEventAdded);
connect(addResultWindow, &AddResultWindow::resultAdded, this, &MainWindow::handleResultAdded);
loadData();
}
MainWindow::~MainWindow()
{
delete ui;
delete addCollegeWindow;
delete addEventWindow;
delete addResultWindow;
delete displayResultsWindow;
delete displayDataWindow;
}
void MainWindow::addCollege(const QString& name) {
College* existingCollege = collegeHead;
while (existingCollege != nullptr) {
if (existingCollege->name == name) {
QMessageBox::information(this, "提示", QString("学院 %1 已存在,编号为 %2").arg(name).arg(existingCollege->id));
return;
}
existingCollege = existingCollege->next;
}
College* newCollege = new College;
newCollege->id = ++collegeCount;
newCollege->name = name;
newCollege->points = 0;
newCollege->next = collegeHead;
collegeHead = newCollege;
}
void MainWindow::addEvent(const QString& name, int isTopFive, bool isMale) {
Event* existingEvent = eventHead;
while (existingEvent != nullptr) {
if (existingEvent->name == name && ((existingEvent->isMale && isMale) || (!existingEvent->isMale && !isMale))) {
QMessageBox::information(this, "提示", QString("项目 %1 已存在,编号为 %2").arg(name).arg(existingEvent->id));
return;
}
existingEvent = existingEvent->next;
}
Event* newEvent = new Event;
newEvent->name = name;
newEvent->isTopFive = isTopFive;
newEvent->isMale = isMale;
newEvent->next = eventHead;
eventHead = newEvent;
// 调整所有项目编号
int maleEventCount = 0;
Event* event = eventHead;
while (event != nullptr) {
if (event->isMale == 1) {
event->id = ++maleEventCount;
}
event = event->next;
}
event = eventHead;
while (event !=nullptr){
if (event->isMale == 0){
event->id = ++maleEventCount;
}
event = event->next;
}
// 重新排序项目
Event* sortedEvents[100];
int count = 0;
event = eventHead;
while (event != nullptr) {
sortedEvents[count++] = event;
event = event->next;
}
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (sortedEvents[j]->id > sortedEvents[j + 1]->id) {
Event* temp = sortedEvents[j];
sortedEvents[j] = sortedEvents[j + 1];
sortedEvents[j + 1] = temp;
}
}
}
eventHead = sortedEvents[0];
for (int i = 0; i < count - 1; i++) {
sortedEvents[i]->next = sortedEvents[i + 1];
}
sortedEvents[count - 1]->next = nullptr;
}
void MainWindow::addResult(int collegeId, int eventId, int rank) {
Result* newResult = new Result;
newResult->collegeId = collegeId;
newResult->eventId = eventId;
newResult->rank = rank;
newResult->next = resultHead;
resultHead = newResult;
// 更新学院积分
College* college = collegeHead;
while (college != nullptr) {
if (college->id == collegeId) {
Event* event = eventHead;
while (event != nullptr) {
if (event->id == eventId) {
if (event->isTopFive) {
if (rank == 1) college->points += 7;
else if (rank == 2) college->points += 5;
else if (rank == 3) college->points += 3;
else if (rank == 4) college->points += 2;
else if (rank == 5) college->points += 1;
} else {
if (rank == 1) college->points += 5;
else if (rank == 2) college->points += 3;
else if (rank == 3) college->points += 2;
}
break;
}
event = event->next;
}
break;
}
college = college->next;
}
}
void MainWindow::displayResults() {
// 按积分排序
College* sortedColleges[100];
int count = 0;
College* college = collegeHead;
while (college != nullptr) {
sortedColleges[count++] = college;
college = college->next;
}
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (sortedColleges[j]->points < sortedColleges[j + 1]->points) {
College* temp = sortedColleges[j];
sortedColleges[j] = sortedColleges[j + 1];
sortedColleges[j + 1] = temp;
}
}
}
// 显示总排名
QList<QList<QString>> results;
for (int i = 0; i < count; i++) {
QList<QString> row;
row << QString::number(i + 1) << sortedColleges[i]->name << QString::number(sortedColleges[i]->points);
results.append(row);
}
displayResultsWindow->displayResults(results);
displayResultsWindow->show();
}
void MainWindow::displayCollegesAndEvents() {
// 按学院编号排序
College* sortedColleges[100];
int count = 0;
College* college = collegeHead;
while (college != nullptr) {
sortedColleges[count++] = college;
college = college->next;
}
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (sortedColleges[j]->id < sortedColleges[j + 1]->id) {
College* temp = sortedColleges[j];
sortedColleges[j] = sortedColleges[j + 1];
sortedColleges[j + 1] = temp;
}
}
}
// 逆序显示学院和项目数据
QList<QList<QString>> data;
for (int i = count - 1; i >= 0; i--) {
QList<QString> row;
row << "学院" << sortedColleges[i]->name << QString::number(sortedColleges[i]->id);
data.append(row);
}
Event* sortedEvents[100];
int eventCount = 0;
Event* event = eventHead;
while (event != nullptr) {
sortedEvents[eventCount++] = event;
event = event->next;
}
for (int i = 0; i < eventCount - 1; i++) {
for (int j = 0; j < eventCount - i - 1; j++) {
if (sortedEvents[j]->id < sortedEvents[j + 1]->id) {
Event* temp = sortedEvents[j];
sortedEvents[j] = sortedEvents[j + 1];
sortedEvents[j + 1] = temp;
}
}
}
for (int i = eventCount - 1; i >= 0; i--) {
QList<QString> row;
row << "项目" << sortedEvents[i]->name << QString::number(sortedEvents[i]->id);
data.append(row);
}
displayDataWindow->displayData(data);
displayDataWindow->show();
}
void MainWindow::displayResultsByEvent() {
// 按项目编号逆序排序
QList<QList<QString>> data;
Result* result = resultHead;
while (result != nullptr) {
QList<QString> row;
Event* event = eventHead;
while (event != nullptr) {
if (event->id == result->eventId) {
row << event->name;
break;
}
event = event->next;
}
College* college = collegeHead;
while (college != nullptr) {
if (college->id == result->collegeId) {
row << college->name;
break;
}
college = college->next;
}
row << QString::number(result->rank);
data.append(row);
result = result->next;
}
displayDataWindow->displayResultsByEvent(data);
displayDataWindow->show();
}
void MainWindow::loadData() {
QFile file("data.txt");
if (!file.exists()) {
// 如果文件不存在,则创建一个空的 data.txt 文件
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(this, "错误", "无法创建 data.txt 文件");
return;
}
file.close();
}
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::warning(this, "错误", "无法打开文件进行读取");
return;
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(" ");
if (fields[0] == "C") {
int id = fields[1].toInt();
QString name = fields[2];
int points = fields[3].toInt();
addCollege(name);
collegeHead->points = points;
} else if (fields[0] == "E") {
int id = fields[1].toInt();
QString name = fields[2];
int isTopFive = fields[3].toInt();
addEvent(name, isTopFive, id % 2 == 1);
} else if (fields[0] == "R") {
int collegeId = fields[1].toInt();
int eventId = fields[2].toInt();
int rank = fields[3].toInt();
addResult(collegeId, eventId, rank);
}
}
file.close();
}
void MainWindow::saveData() {
QFile file("data.txt");
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(this, "错误", "无法打开文件进行写入");
return;
}
QTextStream out(&file);
College* college = collegeHead;
while (college != nullptr) {
out << "C " << college->id << " " << college->name << " " << college->points << "\n";
college = college->next;
}
Event* event = eventHead;
while (event != nullptr) {
out << "E " << event->id << " " << event->name << " " << event->isTopFive << "\n";
event = event->next;
}
Result* result = resultHead;
while (result != nullptr) {
out << "R " << result->collegeId << " " << result->eventId << " " << result->rank << "\n";
result = result->next;
}
file.close();
}
void MainWindow::modifyCollege(int id, const QString& newName) {
College* college = collegeHead;
while (college != nullptr) {
if (college->id == id) {
college->name = newName;
QMessageBox::information(this, "提示", QString("学院 %1 已修改为 %2").arg(id).arg(newName));
return;
}
college = college->next;
}
QMessageBox::warning(this, "错误", QString("未找到编号为 %1 的学院").arg(id));
}
void MainWindow::modifyEvent(int id, const QString& newName, int isTopFive) {
Event* event = eventHead;
while (event != nullptr) {
if (event->id == id) {
event->name = newName;
event->isTopFive = isTopFive;
QMessageBox::information(this, "提示", QString("项目 %1 已修改为 %2").arg(id).arg(newName));
return;
}
event = event->next;
}
QMessageBox::warning(this, "错误", QString("未找到编号为 %1 的项目").arg(id));
}
void MainWindow::deleteResult(int collegeId, int eventId) {
Result* prevResult = nullptr;
Result* result = resultHead;
while (result != nullptr) {
if (result->collegeId == collegeId && result->eventId == eventId) {
// 更新学院积分
College* college = collegeHead;
while (college != nullptr) {
if (college->id == collegeId) {
Event* event = eventHead;
while (event != nullptr) {
if (event->id == eventId) {
if (event->isTopFive) {
if (result->rank == 1) college->points -= 7;
else if (result->rank == 2) college->points -= 5;
else if (result->rank == 3) college->points -= 3;
else if (result->rank == 4) college->points -= 2;
else if (result->rank == 5) college->points -= 1;
} else {
if (result->rank == 1) college->points -= 5;
else if (result->rank == 2) college->points -= 3;
else if (result->rank == 3) college->points -= 2;
}
break;
}
event = event->next;
}
break;
}
college = college->next;
}
// 删除结果节点
if (prevResult == nullptr) {
resultHead = result->next;
} else {
prevResult->next = result->next;
}
free(result);
QMessageBox::information(this, "提示", QString("已删除学院 %1 的项目 %2 的名次和积分").arg(collegeId).arg(eventId));
saveData(); // 保存数据
return;
}
prevResult = result;
result = result->next;
}
QMessageBox::warning(this, "错误", QString("未找到学院 %1 的项目 %2 的名次和积分").arg(collegeId).arg(eventId));
}
void MainWindow::handleCollegeAdded(const QString &name)
{
addCollege(name);
saveData();
}
void MainWindow::handleEventAdded(const QString &name, int isTopFive, bool isMale)
{
addEvent(name, isTopFive, isMale);
saveData();
}
void MainWindow::handleResultAdded(int collegeId, int eventId, int rank)
{
addResult(collegeId, eventId, rank);
saveData();
}
void MainWindow::on_addCollegeButton_clicked()
{
qDebug() << "Add College Button clicked";
addCollegeWindow->show();
}
void MainWindow::on_addEventButton_clicked()
{
qDebug() << "Add Event Button clicked";
addEventWindow->show();
}
void MainWindow::on_addResultButton_clicked()
{
qDebug() << "Add Result Button clicked";
addResultWindow->show();
}
void MainWindow::on_displayResultsButton_clicked()
{
qDebug() << "Display Results Button clicked";
displayResults();
}
void MainWindow::on_displayDataButton_clicked()
{
qDebug() << "Display Data Button clicked";
displayCollegesAndEvents();
}
void MainWindow::on_displayResultsByEventButton_clicked()
{
qDebug() << "Display Results By Event Button clicked";
displayResultsByEvent();
}
void MainWindow::on_modifyCollegeButton_clicked()
{
qDebug() << "Modify College Button clicked";
bool ok;
int id = QInputDialog::getInt(this, "修改学院", "请输入学院编号:", 0, 0, 10000, 1, &ok);
if (!ok) return;
QString newName = QInputDialog::getText(this, "修改学院", "请输入新的学院名称:", QLineEdit::Normal, "", &ok);
if (!ok || newName.isEmpty()) return;
modifyCollege(id, newName);
}
void MainWindow::on_modifyEventButton_clicked()
{
qDebug() << "Modify Event Button clicked";
bool ok;
int id = QInputDialog::getInt(this, "修改项目", "请输入项目编号:", 0, 0, 10000, 1, &ok);
if (!ok) return;
QString newName = QInputDialog::getText(this, "修改项目", "请输入新的项目名称:", QLineEdit::Normal, "", &ok);
if (!ok || newName.isEmpty()) return;
int isTopFive = QInputDialog::getInt(this, "修改项目", "是否取前五名(1是, 0否):", 0, 0, 1, 1, &ok);
if (!ok) return;
modifyEvent(id, newName, isTopFive);
}
void MainWindow::on_deleteResultButton_clicked()
{
qDebug() << "Delete Result Button clicked";
bool ok;
int collegeId = QInputDialog::getInt(this, "删除比赛结果", "请输入学院编号:", 0, 0, 10000, 1, &ok);
if (!ok) return;
int eventId = QInputDialog::getInt(this, "删除比赛结果", "请输入项目编号:", 0, 0, 10000, 1, &ok);
if (!ok) return;
deleteResult(collegeId, eventId);
}
|
2301_80164243/program
|
mainwindow.cpp
|
C++
|
unknown
| 17,868
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "addcollegewindow.h"
#include "addeventwindow.h"
#include "addresultwindow.h"
#include "displayresultswindow.h"
#include "displaydatawindow.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void addCollege(const QString& name);
void addEvent(const QString& name, int isTopFive, bool isMale);
void addResult(int collegeId, int eventId, int rank);
void displayResults();
void displayCollegesAndEvents();
void displayResultsByEvent();
void saveData();
void loadData();
void modifyCollege(int id, const QString& newName);
void modifyEvent(int id, const QString& newName, int isTopFive);
void deleteResult(int collegeId, int eventId);
private slots:
void on_addCollegeButton_clicked();
void on_addEventButton_clicked();
void on_addResultButton_clicked();
void on_displayResultsButton_clicked();
void on_displayDataButton_clicked();
void on_displayResultsByEventButton_clicked(); // 添加此行
void on_modifyCollegeButton_clicked();
void on_modifyEventButton_clicked();
void on_deleteResultButton_clicked();
void handleCollegeAdded(const QString &name);
void handleEventAdded(const QString &name, int isTopFive, bool isMale);
void handleResultAdded(int collegeId, int eventId, int rank);
private:
Ui::MainWindow *ui;
AddCollegeWindow *addCollegeWindow;
AddEventWindow *addEventWindow;
AddResultWindow *addResultWindow;
DisplayResultsWindow *displayResultsWindow;
DisplayDataWindow *displayDataWindow;
struct College {
int id;
QString name;
int points;
College* next;
};
struct Event {
int id;
QString name;
int isTopFive;
int isMale;
Event* next;
};
struct Result {
int collegeId;
int eventId;
int rank;
Result* next;
};
College* collegeHead = nullptr;
Event* eventHead = nullptr;
Result* resultHead = nullptr;
int collegeCount = 0;
int eventCount = 0;
};
#endif // MAINWINDOW_H
|
2301_80164243/program
|
mainwindow.h
|
C++
|
unknown
| 2,360
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D Audio Visualizer</title>
<style>
body { margin: 0; overflow: hidden; }
#controls {
position: absolute;
top: 20px;
left: 20px;
z-index: 100;
color: white;
}
.custom-button {
background: rgba(123, 31, 162, 0.3);
color: white;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
margin: 5px;
border: 1px solid rgba(123, 31, 162, 0.5);
position: relative;
overflow: hidden;
transition: all 0.3s ease;
z-index: 1;
}
.custom-button:hover {
background: rgba(123, 31, 162, 0.6);
box-shadow: 0 0 10px rgba(123, 31, 162, 10);
}
.custom-button::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(
90deg,
transparent,
rgba(255, 255, 255, 0.3),
transparent
);
transition: all 0.7s ease;
z-index: -1;
border-radius: 3px;
}
.custom-button:hover::before {
left: 100%;
}
input[type="file"] { display: none; }
#loading {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 20px;
display: none;
}
#progress-bar {
width: 200px;
height: 10px;
background: #444;
border-radius: 5px;
margin-top: 10px;
overflow: hidden;
}
#progress {
width: 0;
height: 100%;
background: #7b1fa2;
transition: width 0.3s;
}
</style>
</head>
<body>
<div id="controls">
<label class="custom-button" for="audioInput">选择音频</label>
<button class="custom-button" id="playPauseBtn" disabled>播放/暂停</button>
<input type="file" id="audioInput" accept="audio/*" />
<div id="progress-bar">
<div id="progress"></div>
</div>
<div style="margin-top: 10px;">按 <strong>P键</strong> 切换摄像头模式</div>
</div>
<div id="loading">加载中,请稍候...</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js"></script>
<script>
let scene, camera, renderer, analyzer, audioElem, source;
let waveform, ball, isPlaying = false;
const FLUID_COLOR = new THREE.Color(0x7b1fa2);
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// 低频加速相关变量
let lastBassHitTime = 0;
let isBoosting = false;
const BASS_THRESHOLD = 180; // 低频阈值
const BOOST_DURATION = 1000; // 加速持续时间(ms)
const BASE_SPEED = 0.1; // 基础速度
const BOOST_SPEED = 0.3; // 加速速度
const BOOST_SCALE = 1.14514; // 加速时放大倍数
let roadLine, stars, ballTrail = [];
const TRAIL_LENGTH = 10;
let manualCameraControl = false;
let controls;
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enabled = false;
analyzer = audioContext.createAnalyser();
analyzer.fftSize = 256;
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(analyzer.frequencyBinCount * 3);
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
waveform = new THREE.Line(geometry, new THREE.LineBasicMaterial({
color: FLUID_COLOR,
transparent: true,
opacity: 0.8
}));
scene.add(waveform);
const ballGeometry = new THREE.SphereGeometry(0.5, 32, 32);
const ballMaterial = new THREE.ShaderMaterial({
uniforms: {
glowColor: { value: FLUID_COLOR },
intensity: { value: 3.0 }
},
vertexShader: `
varying vec3 vPosition;
void main() {
vPosition = position;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 glowColor;
uniform float intensity;
varying vec3 vPosition;
void main() {
float glow = pow(1.0 - length(vPosition), 3.0) * intensity;
gl_FragColor = vec4(glowColor * glow, glow);
}
`,
transparent: true,
blending: THREE.AdditiveBlending
});
ball = new THREE.Mesh(ballGeometry, ballMaterial);
scene.add(ball);
for (let i = 0; i < TRAIL_LENGTH; i++) {
const trailBall = ball.clone();
trailBall.material = ball.material.clone();
trailBall.material.uniforms.intensity.value = 3.0 * (1 - i / TRAIL_LENGTH);
trailBall.material.transparent = true;
trailBall.material.opacity = 1 - i / TRAIL_LENGTH;
ballTrail.push(trailBall);
scene.add(trailBall);
}
const roadGeometry = new THREE.BufferGeometry();
const roadPositions = new Float32Array([-10000, -2, 0, 10000, -2, 0]);
roadGeometry.setAttribute('position', new THREE.BufferAttribute(roadPositions, 3));
roadLine = new THREE.Line(roadGeometry, new THREE.LineBasicMaterial({ color: 0xffffff }));
scene.add(roadLine);
const starGeometry = new THREE.BufferGeometry();
const starPositions = [];
for (let i = 0; i < 18000; i++) {
starPositions.push(
(Math.random() - 0.5) * 9000,
(Math.random() - 0.5) * 9000,
(Math.random() - 0.5) * 9000
);
}
starGeometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(starPositions), 3));
stars = new THREE.Points(starGeometry, new THREE.PointsMaterial({ color: 0xffffff, size: 1.2 }));
scene.add(stars);
scene.add(new THREE.AmbientLight(0x444444));
const pointLight = new THREE.PointLight(FLUID_COLOR, 1, 200);
pointLight.position.set(0, 10, 10);
scene.add(pointLight);
camera.position.set(0, 5, 15);
camera.lookAt(0, 0, 0);
}
function updateVisualization() {
if (!isPlaying) return;
const dataArray = new Uint8Array(analyzer.frequencyBinCount);
analyzer.getByteFrequencyData(dataArray);
const time = Date.now() * 0.001;
const now = Date.now();
// 检测低频鼓声(前10个频段)
let bassEnergy = 0;
for (let i = 0; i < 10; i++) {
bassEnergy += dataArray[i];
}
bassEnergy /= 10;
// 低频触发加速
if (bassEnergy > BASS_THRESHOLD && now - lastBassHitTime > BOOST_DURATION) {
lastBassHitTime = now;
isBoosting = true;
setTimeout(() => isBoosting = false, BOOST_DURATION);
}
// 更新波形
const positions = waveform.geometry.attributes.position.array;
for (let i = 0; i < positions.length; i += 3) {
const idx = i / 3;
const value = dataArray[idx] / 128;
positions[i] = (ball.position.x - 3) + (idx * 0.15);
positions[i + 1] = Math.sin(time + idx * 0.2) * value * 1.5;
positions[i + 2] = Math.cos(time + idx * 0.2) * value * 1.5;
}
waveform.geometry.attributes.position.needsUpdate = true;
// 更新小球 - 根据是否加速调整速度和大小
const currentSpeed = isBoosting ? BOOST_SPEED : BASE_SPEED;
const avg = dataArray.reduce((a, b) => a + b) / dataArray.length;
ball.position.x += currentSpeed;
ball.position.y = Math.sin(time * 2) * (avg / 50);
ball.position.z = Math.cos(time * 2) * (avg / 50);
const scaleFactor = isBoosting ? BOOST_SCALE : 1;
ball.scale.set(
(1 + avg / 150) * scaleFactor,
(1 + avg / 150) * scaleFactor,
(1 + avg / 150) * scaleFactor
);
// 更新残影
for (let i = TRAIL_LENGTH - 1; i > 0; i--) {
ballTrail[i].position.copy(ballTrail[i - 1].position);
ballTrail[i].scale.copy(ballTrail[i - 1].scale);
ballTrail[i].material.opacity = ballTrail[i - 1].material.opacity * 0.8;
}
ballTrail[0].position.copy(ball.position);
ballTrail[0].scale.copy(ball.scale);
ballTrail[0].material.opacity = 1;
// 公路线位置
const roadPositions = roadLine.geometry.attributes.position.array;
roadPositions[0] = ball.position.x - 10000;
roadPositions[3] = ball.position.x + 10000;
roadLine.geometry.attributes.position.needsUpdate = true;
// 自动跟随模式
if (!manualCameraControl) {
camera.position.x = ball.position.x;
camera.lookAt(ball.position.x + 5, ball.position.y, ball.position.z);
}
}
function animate() {
requestAnimationFrame(animate);
updateVisualization();
if (manualCameraControl) controls.update();
renderer.render(scene, camera);
}
window.addEventListener('keydown', (e) => {
if (e.key.toLowerCase() === 'p') {
manualCameraControl = !manualCameraControl;
controls.enabled = manualCameraControl;
controls.target.copy(ball.position);
}
});
document.getElementById('audioInput').addEventListener('change', function (e) {
const file = e.target.files[0];
const url = URL.createObjectURL(file);
document.getElementById('loading').style.display = 'block';
document.getElementById('playPauseBtn').disabled = true;
audioElem = new Audio(url);
audioElem.addEventListener('canplaythrough', () => {
document.getElementById('loading').style.display = 'none';
document.getElementById('playPauseBtn').disabled = false;
document.getElementById('progress').style.width = '100%';
});
audioElem.addEventListener('timeupdate', () => {
const progress = (audioElem.currentTime / audioElem.duration) * 100;
document.getElementById('progress').style.width = `${progress}%`;
});
audioElem.addEventListener('ended', () => {
isPlaying = false;
document.getElementById('playPauseBtn').disabled = true;
});
source = audioContext.createMediaElementSource(audioElem);
source.connect(analyzer);
analyzer.connect(audioContext.destination);
document.getElementById('playPauseBtn').onclick = async () => {
if (audioContext.state === 'suspended') await audioContext.resume();
isPlaying ? audioElem.pause() : audioElem.play();
isPlaying = !isPlaying;
};
});
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
init();
animate();
</script>
</body>
</html>
|
2301_80165137/Vector_Starball_v1
|
Victor Starball - speed.html
|
HTML
|
unknown
| 13,325
|
pub fn new_count_distinct(input_str: &str) -> usize {
todo!()
}
|
2301_80155689/myRustContest
|
exercises/solution1/src/count_distinct.rs
|
Rust
|
unknown
| 68
|
mod count_distinct;
fn main() {
let input_str: &str = "a,b,cd,b,e,e,d,a";
let count = count_distinct::new_count_distinct(input_str);
println!("count: {count}");
}
|
2301_80155689/myRustContest
|
exercises/solution1/src/main.rs
|
Rust
|
unknown
| 176
|
// src/tests.rs
mod count_distinct;
#[cfg(test)]
mod tests {
use super::count_distinct::new_count_distinct;
// 定义测试用例和预期结果
const TEST_CASES: &[(&str, usize)] = &[
("a,b,c,a,e,cd", 5),
("a,b,a,a,e,cd", 4),
("j,a,c,d,e,z", 6),
("a,b,c,好,好,爱", 5),
("a,b,c,0,e,cd", 6),
];
// 定义一个测试函数来验证每个测试用例
#[test]
fn test_count() {
let mut total_score = 0.0;
for (input1, expected) in TEST_CASES {
let result = new_count_distinct(*input1);
if result == *expected {
total_score += 20.0;
}
}
println!("Total score: {:.2}", total_score);
assert_eq!(100.00, total_score);
}
}
|
2301_80155689/myRustContest
|
exercises/solution1/src/tests.rs
|
Rust
|
unknown
| 783
|
pub fn convert_base(num_str: &str, to_base: u32) -> String {
// TODO: 这里写逻辑
todo!()
}
|
2301_80155689/myRustContest
|
exercises/solution2/src/converter.rs
|
Rust
|
unknown
| 104
|
mod converter;
fn main() {
let num_str = "9(10)";
let base_to: u32 = 8;
let result = converter::convert_base(num_str, base_to);
println!("{} -> {}", num_str, result);
}
|
2301_80155689/myRustContest
|
exercises/solution2/src/main.rs
|
Rust
|
unknown
| 186
|
// src/tests.rs
mod converter;
#[cfg(test)]
mod tests {
use super::converter::convert_base;
// 定义测试用例和预期结果
const TEST_CASES: &[(&str, u32, &str)] = &[
("10(2)", 10, "2"),
("9(10)", 8, "11"),
("1111(2)", 15, "10"),
("10(7)", 9, "7"),
("12(10)", 16, "c"),
];
// 定义一个测试函数来验证每个测试用例
#[test]
fn test_converter() {
let mut total_score = 0.0;
for (input1, input2, expected) in TEST_CASES {
let result = convert_base(*input1, *input2);
if result == *expected {
total_score += 20.0;
}
}
println!("Total score: {:.2}", total_score);
assert_eq!(100.00, total_score);
}
}
|
2301_80155689/myRustContest
|
exercises/solution2/src/tests.rs
|
Rust
|
unknown
| 784
|
pub fn new_birthday_probability(n: u32) -> f64 {
// TODO: 这里写逻辑
todo!()
}
|
2301_80155689/myRustContest
|
exercises/solution3/src/calc_logic.rs
|
Rust
|
unknown
| 92
|
mod calc_logic;
fn main() {
// 更改这个值来测试不同的人数
let n: u32 = 78;
let probability = calc_logic::new_birthday_probability(n);
println!(
"在 {} 个人中,有两个人在同一天过生日的概率是 {:.4}",
n,
probability
);
}
|
2301_80155689/myRustContest
|
exercises/solution3/src/main.rs
|
Rust
|
unknown
| 296
|
mod calc_logic;
#[cfg(test)]
mod tests {
use super::calc_logic::new_birthday_probability;
// 定义测试用例和预期结果
const TEST_CASES: &[(u32, f64)] = &[
(23, 0.5073),
(30, 0.7063),
(50, 0.9704),
(78, 0.9999),
(100, 1.0000),
];
// 定义一个测试函数来验证每个测试用例
#[test]
fn test_new_birthday_probability() {
let mut total_score = 0.0;
for (input, expected) in TEST_CASES {
let result = new_birthday_probability(*input);
// 定义一个容差值
let tolerance = 0.0001;
if (result - expected).abs() < tolerance {
total_score += 20.0;
} else {
println!(
"Test case n={} failed. Expected {:.4}, got {:.4}",
input, expected, result
);
}
}
println!("Total score: {:.2}", total_score);
assert_eq!(100.00, total_score);
}
}
|
2301_80155689/myRustContest
|
exercises/solution3/src/tests.rs
|
Rust
|
unknown
| 1,023
|
mod rec_mc;
fn main() {
let amount = 93u32;
let cashe_num = rec_mc::dp_rec_mc(amount);
println!("{cashe_num}");
}
|
2301_80155689/myRustContest
|
exercises/solution4/src/main.rs
|
Rust
|
unknown
| 127
|
pub fn dp_rec_mc(amount: u32) -> u32 {
// TODO: 这里写逻辑
todo!()
}
|
2301_80155689/myRustContest
|
exercises/solution4/src/rec_mc.rs
|
Rust
|
unknown
| 82
|
// src/tests.rs
mod rec_mc;
#[cfg(test)]
mod tests {
use super::rec_mc::dp_rec_mc;
// 定义测试用例和预期结果
// const CASHES: [u32; 8] = [1, 2, 5, 10, 20, 30, 50, 100];
const TEST_CASES: &[(u32, u32)] = &[
(90, 3),
(93, 5),
(101, 2),
(102, 2),
(0, 0),
];
// 定义一个测试函数来验证每个测试用例
#[test]
fn test_count() {
let mut total_score = 0.0;
for (input1, expected) in TEST_CASES {
let result = dp_rec_mc(*input1);
if result == *expected {
total_score += 20.0;
}
}
println!("Total score: {:.2}", total_score);
assert_eq!(100.00, total_score);
}
}
|
2301_80155689/myRustContest
|
exercises/solution4/src/tests.rs
|
Rust
|
unknown
| 746
|
pub fn odd_fibnacci_sum(threshold: u32) -> u32 {
// TODO: 这里写逻辑
todo!()
}
|
2301_80155689/myRustContest
|
exercises/solution5/src/fibnacci.rs
|
Rust
|
unknown
| 92
|
mod fibnacci;
fn main() {
let num = 20;
let sum = fibnacci::odd_fibnacci_sum(num);
println!("{sum}");
}
|
2301_80155689/myRustContest
|
exercises/solution5/src/main.rs
|
Rust
|
unknown
| 117
|
// src/tests.rs
mod fibnacci;
#[cfg(test)]
mod tests {
use super::fibnacci::odd_fibnacci_sum;
// 定义测试用例和预期结果
const TEST_CASES: &[(u32, u32)] = &[
(20, 23),
(22, 44),
(30, 44),
(40, 44),
(56, 99),
];
// 定义一个测试函数来验证每个测试用例
#[test]
fn test_count() {
let mut total_score = 0.0;
for (input1, expected) in TEST_CASES {
let result = odd_fibnacci_sum(*input1);
if result == *expected {
total_score += 20.0;
}
}
println!("Total score: {:.2}", total_score);
assert_eq!(100.00, total_score);
}
}
|
2301_80155689/myRustContest
|
exercises/solution5/src/tests.rs
|
Rust
|
unknown
| 705
|
use std::sync::Arc;
use std::{process::Command, sync::Mutex};
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use std::fs;
#[tokio::main]
async fn main() {
let solution1 = format!("
// src/tests.rs
mod count_distinct;
#[cfg(test)]
mod tests {{
use super::count_distinct::new_count_distinct;
// 定义测试用例和预期结果
const TEST_CASES: &[(&str, usize)] = &[
(\"a,b,c,a,e,cd\", 5),
(\"a,b,a,a,e,cd\", 4),
(\"j,a,c,d,e,z\", 6),
(\"a,b,c,好,好,爱\", 5),
(\"a,b,c,0,e,cd\", 6),
];
// 定义一个测试函数来验证每个测试用例
#[test]
fn test_count() {{
let mut total_score = 0.0;
for (input1, expected) in TEST_CASES {{
let result = new_count_distinct(*input1);
if result == *expected {{
total_score += 20.0;
}}
}}
println!(\"Total score: {{:.2}}\", total_score);
assert_eq!(100.00, total_score);
}}
}}
");
let solution2 = format!("
// src/tests.rs
mod converter;
#[cfg(test)]
mod tests {{
use super::converter::convert_base;
// 定义测试用例和预期结果
const TEST_CASES: &[(&str, u32, &str)] = &[
(\"10(2)\", 10, \"2\"),
(\"9(10)\", 8, \"11\"),
(\"1111(2)\", 15, \"10\"),
(\"10(7)\", 9, \"7\"),
(\"12(10)\", 16, \"c\"),
];
// 定义一个测试函数来验证每个测试用例
#[test]
fn test_converter() {{
let mut total_score = 0.0;
for (input1, input2, expected) in TEST_CASES {{
let result = convert_base(*input1, *input2);
if result == *expected {{
total_score += 20.0;
}}
}}
println!(\"Total score: {{:.2}}\", total_score);
assert_eq!(100.00, total_score);
}}
}}
");
let solution3 = format!("
mod calc_logic;
#[cfg(test)]
mod tests {{
use super::calc_logic::new_birthday_probability;
// 定义测试用例和预期结果
const TEST_CASES: &[(u32, f64)] = &[
(23, 0.5073),
(30, 0.7063),
(50, 0.9704),
(78, 0.9999),
(100, 1.0000),
];
// 定义一个测试函数来验证每个测试用例
#[test]
fn test_new_birthday_probability() {{
let mut total_score = 0.0;
for (input, expected) in TEST_CASES {{
let result = new_birthday_probability(*input);
// 定义一个容差值
let tolerance = 0.0001;
if (result - expected).abs() < tolerance {{
total_score += 20.0;
}} else {{
println!(
\"Test case n={{}} failed. Expected {{:.4}}, got {{:.4}}\",
input, expected, result
);
}}
}}
println!(\"Total score: {{:.2}}\", total_score);
assert_eq!(100.00, total_score);
}}
}}
");
let solution4 = format!("
// src/tests.rs
mod rec_mc;
#[cfg(test)]
mod tests {{
use super::rec_mc::dp_rec_mc;
// 定义测试用例和预期结果
const TEST_CASES: &[(u32, u32)] = &[
(90, 3),
(93, 5),
(101, 2),
(102, 2),
(0, 0),
];
// 定义一个测试函数来验证每个测试用例
#[test]
fn test_count() {{
let mut total_score = 0.0;
for (input1, expected) in TEST_CASES {{
let result = dp_rec_mc(*input1);
if result == *expected {{
total_score += 20.0;
}}
}}
println!(\"Total score: {{:.2}}\", total_score);
assert_eq!(100.00, total_score);
}}
}}
");
let solution5 = format!("
// src/tests.rs
mod fibnacci;
#[cfg(test)]
mod tests {{
use super::fibnacci::odd_fibnacci_sum;
// 定义测试用例和预期结果
const TEST_CASES: &[(u32, u32)] = &[
(20, 23),
(22, 44),
(30, 44),
(40, 44),
(56, 99),
];
// 定义一个测试函数来验证每个测试用例
#[test]
fn test_count() {{
let mut total_score = 0.0;
for (input1, expected) in TEST_CASES {{
let result = odd_fibnacci_sum(*input1);
if result == *expected {{
total_score += 20.0;
}}
}}
println!(\"Total score: {{:.2}}\", total_score);
assert_eq!(100.00, total_score);
}}
}}
");
let mut test_map = HashMap::<String, Solution>::new();
test_map.insert("solution1".to_owned(), Solution{ score: 20 ,test: solution1});
test_map.insert("solution2".to_owned(), Solution{ score: 20 ,test: solution2});
test_map.insert("solution3".to_owned(), Solution{ score: 20 ,test: solution3});
test_map.insert("solution4".to_owned(), Solution{ score: 20 ,test: solution4});
test_map.insert("solution5".to_owned(), Solution{ score: 20 ,test: solution5});
let exercise_check_list = Arc::new(Mutex::new(
ExerciseCheckList {
statistics: ExerciseStatistics {
total_exercations: 100,
total_succeeds: 0,
total_failures: 0,
total_time: 0,
}
}
));
let mut tasks = Vec::new();
for (key, solution) in test_map {
// 每个solution的结果都需要写入,需要clone下
let exercise_check_list_ref = Arc::clone(&exercise_check_list);
let score = solution.score;
let value = solution.test.clone();
let t = tokio::task::spawn(async move {
// 写测试代码
let path = format!("exercises/{}/src/tests.rs", key);
fs::write(path, value).expect("Failed to write test file");
// 执行测试代码
let output = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(["/C", format!("cargo test -p {}", key).as_str()])
.output()
.expect("failed to execute process")
} else {
Command::new("sh")
.arg("-c")
.arg(format!("cargo test -p {}", key).as_str())
.output()
.expect("failed to execute process")
};
// 每通过一个加20分(score)
let stdout = String::from_utf8(output.stdout).unwrap();
println!("stdout: {}", stdout);
if stdout.contains("test result: ok. 1 passed") {
exercise_check_list_ref.lock().unwrap().statistics.total_succeeds += score;
}
});
tasks.push(t);
}
// 异步执行所有测试
for task in tasks { task.await.unwrap(); }
let serialized = serde_json::to_string_pretty(&*exercise_check_list.lock().unwrap()).unwrap();
fs::write(".atomgit/result/check_result.json", serialized).unwrap();
}
struct Solution {
score: u32,
test: String,
}
#[derive(Deserialize, Serialize)]
pub struct ExerciseStatistics {
pub total_exercations: u32,
pub total_succeeds: u32,
pub total_failures: u32,
pub total_time: u32,
}
#[derive(Deserialize, Serialize)]
pub struct ExerciseCheckList {
pub statistics: ExerciseStatistics
}
|
2301_80155689/myRustContest
|
src/main.rs
|
Rust
|
unknown
| 7,250
|
import os
import pandas as pd
def convert_xlsx_to_csv(folder_path):
# 遍历指定文件夹
for root, dirs, files in os.walk(folder_path):
for file in files:
# 检查文件是否为 xlsx 格式
if file.endswith('.xlsx'):
# 构建完整的文件路径
xlsx_file_path = os.path.join(root, file)
# 读取 xlsx 文件
try:
# 指定使用 openpyxl 引擎读取 xlsx 文件
df = pd.read_excel(xlsx_file_path, engine='openpyxl')
# 生成对应的 csv 文件路径
csv_file_name = os.path.splitext(file)[0] + '.csv'
csv_file_path = os.path.join(root, csv_file_name)
# 将数据保存为 csv 文件
df.to_csv(csv_file_path, index=False)
print(f"成功将 {xlsx_file_path} 转换为 {csv_file_path}")
except Exception as e:
print(f"处理 {xlsx_file_path} 时出现错误: {e}")
if __name__ == "__main__":
# 指定文件夹路径,请替换为实际路径
folder = "D:\\User\\LIU\\xlsx"
convert_xlsx_to_csv(folder)
|
2301_80171041/jichuang
|
1.py
|
Python
|
unknown
| 1,222
|
// 运行方式:在build中make
#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include"dir.h"
#include"doublelist.h"
#include "lv_my_font.h"
#define BLOCK_SIZE 30
#define SUB_SIZE (BLOCK_SIZE/4)
#define EMPTY 0XFF
// 全局互斥锁,保护游戏状态访问
pthread_mutex_t game_mutex;
// 游戏结束标志
bool game_over = false;
//方块形状
const uint8_t THTROMINOS[7][4][4]={
{//j
{0,0,1,0},
{1,1,1,0},
{0,0,0,0},
{0,0,0,0}
},
{
{1,0,0,0},
{1,1,1,0},
{0,0,0,0},
{0,0,0,0}
},
{
{0,0,0,0},
{1,1,1,1},
{0,0,0,0},
{0,0,0,0}
},
{
{0,1,1,0},
{0,1,1,0},
{0,0,0,0},
{0,0,0,0}
},
{
{0,1,0,0},
{1,1,1,0},
{0,0,0,0},
{0,0,0,0}
},
{
{0,1,1,0},
{1,1,0,0},
{0,0,0,0},
{0,0,0,0}
},
{
{1,1,0,0},
{0,1,1,0},
{0,0,0,0},
{0,0,0,0}
}
};
//图片路径
const char *BLOCK_IMAGES[7]={
"A:L.bmp",
"A:J.bmp",
"A:I.bmp",
"A:O.bmp",
"A:T.bmp",
"A:S.bmp",
"A:Z.bmp"
};
typedef struct
{
//游戏状态
uint8_t board[20][10];//方块容器总共10*20个格子
int current_piece;//当前的方块
int next_piece;//下一个方块
//方块在20*10个格子的位置(x[0-9],y[0-19])和旋转状态(4种[0,1,2,3])
int x,y,rotation;
int bag[7];
int bag_index;
//游戏数据
uint32_t score;//当前分数
uint16_t lines;//消除行数
uint8_t level;//速度
uint32_t fall_speed;
}GameState;
typedef struct
{
lv_obj_t *game_area;
lv_obj_t *next_block;//下一个方块的预览
lv_obj_t *score_label;
lv_obj_t *level_label;
lv_obj_t *lines_label;
//方块图片对象(显示)
lv_obj_t *block_imgs[20][10];
}GameUI;
GameState game;
GameUI ui;
lv_obj_t *my_lv_init_button(lv_obj_t *parent, int x, int y, int w, int h, int color1, int color2, const char *text);
// 渲染定时器回调
static void render_timer_cb(lv_timer_t *timer);
// 游戏线程函数
static void *game_thread_func(void *arg);
//游戏初始化
void game_init();
void create_ui();
//旋转当前的方块
void rotate_piece();
//检查方块状态
bool check_collision(int new_x, int new_y, int new_rotation);
int get_block_pos(int* bx, int* by, int x, int y, int rotation, int piece_type);
//锁住方块(当方块触地或者接触到其他已经固定好的方块时)
void lock_piece();
//清除满了格子的一行
void clear_lines();
void update_game();
void render();
void update_next_preview();
int get_next_from_bag();
void spawn_new_piece();
bool move_piece(int dx,int dy);
//4个按键
static void my_but1_event_cb(lv_event_t *e);
static void my_but2_event_cb(lv_event_t *e);
static void my_but3_event_cb(lv_event_t *e);
static void my_but4_event_cb(lv_event_t *e);
int main(int argc,char *argv[])
{
// 初始化互斥锁
pthread_mutex_init(&game_mutex, NULL);
lv_init();
/*Linux frame buffer device init*/
lv_display_t *disp = lv_linux_fbdev_create();
lv_linux_fbdev_set_file(disp, "/dev/fb0");
// 初始化触摸屏
lv_indev_t *indev = lv_evdev_create(LV_INDEV_TYPE_POINTER, "/dev/input/event6");
// 初始化游戏状态
pthread_mutex_lock(&game_mutex);
game_init();
pthread_mutex_unlock(&game_mutex);
// 创建UI(主线程)
create_ui();
lv_display_set_flush_wait_cb(disp, NULL);
// 创建渲染定时器(主线程,负责UI更新)
lv_timer_t *render_timer = lv_timer_create(render_timer_cb, 50, NULL);
lv_timer_set_repeat_count(render_timer, -1);
// 创建游戏线程(负责逻辑更新)
pthread_t game_thread;
pthread_create(&game_thread, NULL, game_thread_func, NULL);
/*Handle LVGL tasks*/
while (1) {
lv_timer_handler();
usleep(5000);
pthread_mutex_lock(&game_mutex);
bool should_exit = game_over;
pthread_mutex_unlock(&game_mutex);
if(should_exit) {
// 安全地显示游戏结束画面
lv_obj_t *img = lv_img_create(lv_scr_act());
lv_img_set_src(img, "A:game.bmp");
lv_obj_center(img);
// 强制刷新界面
for(int i = 0; i < 3; i++) {
lv_timer_handler();
usleep(10000);
}
// 确保资源释放
pthread_mutex_destroy(&game_mutex);
exit(0);
}
}
return 0;
}
// 创建一个按钮
lv_obj_t *my_lv_init_button(lv_obj_t *parent, int x, int y, int w, int h, int color1, int color2, const char *text)
{
// 创建按钮
lv_obj_t *but = lv_button_create(parent);
// 设置按钮的大小和位置等属性
lv_obj_set_size(but, w, h);
lv_obj_set_pos(but, x, y);
// 按钮样式
static lv_style_t but_style;
lv_style_init(&but_style);
lv_style_set_bg_color(&but_style, lv_color_hex(color1));
lv_style_set_text_color(&but_style, lv_color_hex(color2));
lv_style_set_text_font(&but_style, &lv_font_montserrat_28);
// 添加样式
lv_obj_add_style(but, &but_style, LV_STATE_DEFAULT);
// 给按钮添加标签
lv_obj_t *lab = lv_label_create(but);
lv_label_set_text(lab, text);
return but;
}
//游戏初始化
void game_init()
{
memset(game.board,EMPTY,sizeof(game.board));
game.score=0;
game.level=0;
game.lines=0;
game.fall_speed=1000;
srand(time(NULL));
game.current_piece=rand()%7;
game.next_piece=rand()%7;
game.x=3;
game.y=-1;//顶部外出现
game.rotation=0;
for(int i=0;i<7;i++)
{
game.bag[i]=i;
}
game.bag_index=7;
game.current_piece=get_next_from_bag();
game.next_piece=get_next_from_bag();
}
//随机下一个方块
int get_next_from_bag()
{
if(game.bag_index>=7)
{
for(int i=6;i>0;i--)
{
int j=rand()%(i+1);
int temp=game.bag[j];
game.bag[j]=game.bag[i];
game.bag[i]=temp;
}
game.bag_index=0;
}
return game.bag[game.bag_index++];
}
// 游戏线程函数:处理自动下落逻辑
static void *game_thread_func(void *arg) {
while(1) {
pthread_mutex_lock(&game_mutex);
if(game_over) {
pthread_mutex_unlock(&game_mutex);
break;
}
bool need_render = false;
// 只更新游戏状态,不操作UI
if(!move_piece(0,1)) {
lock_piece();
clear_lines();
spawn_new_piece();
}
uint32_t sleep_ms = game.fall_speed;
pthread_mutex_unlock(&game_mutex);
if(need_render) {
lv_timer_handler();
}
usleep(sleep_ms * 1000);
}
return NULL;
}
// 渲染定时器回调:更新UI(主线程执行)
static void render_timer_cb(lv_timer_t *timer) {
pthread_mutex_lock(&game_mutex);
// 只更新数据,不直接操作UI
static uint32_t last_score = 0;
static uint16_t last_lines = 0;
static uint8_t last_level = 0;
static int last_next_piece = -1;
if(game.score != last_score) {
char score_str[20];
sprintf(score_str,"score:%lu",game.score);
lv_label_set_text(ui.score_label,score_str);
last_score = game.score;
}
if(game.lines != last_lines) {
char lines_str[20];
sprintf(lines_str,"lines:%u",game.lines);
lv_label_set_text(ui.lines_label,lines_str);
last_lines = game.lines;
}
int current_level = (game.lines/10)+1;
if(current_level != last_level) {
char level_str[20];
sprintf(level_str,"speed:%d",current_level);
lv_label_set_text(ui.level_label,level_str);
last_level = current_level;
}
if(game.next_piece != last_next_piece) {
update_next_preview();
last_next_piece = game.next_piece;
}
render();
pthread_mutex_unlock(&game_mutex);
}
//游戏逻辑更新
void update_game()
{
if(!move_piece(0,1))//如果方块无法下移
{
lock_piece(); // 锁定当前方块
clear_lines(); // 清除满行
spawn_new_piece(); // 生成新方块
}
}
void render()
{
// 隐藏所有方块
for(int y=0;y<20;y++)
{
for(int x=0;x<10;x++)
{
lv_obj_add_flag(ui.block_imgs[y][x],LV_OBJ_FLAG_HIDDEN);
}
}
// 绘制已锁定的方块
for(int y=0;y<20;y++)
{
for(int x=0;x<10;x++)
{
if(game.board[y][x]!=EMPTY)//有方块
{
lv_img_set_src(ui.block_imgs[y][x],BLOCK_IMAGES[game.board[y][x]]);
lv_obj_clear_flag(ui.block_imgs[y][x],LV_OBJ_FLAG_HIDDEN);
}
}
}
// 绘制当前活动方块
for(int py=0;py<4;py++)
{
for(int px=0;px<4;px++)
{
int block_value;
switch (game.rotation % 4) {
case 0:
block_value = THTROMINOS[game.current_piece][py][px];
break;
case 1:
block_value = THTROMINOS[game.current_piece][px][3 - py];
break;
case 2:
block_value = THTROMINOS[game.current_piece][3 - py][3 - px];
break;
case 3:
block_value = THTROMINOS[game.current_piece][3 - px][py];
break;
}
if (block_value) {
int bx=game.x+px;
int by=game.y+py;
if(by>=0&&by<20&&bx>=0&&bx<10)//在有效区域内
{
lv_img_set_src(ui.block_imgs[by][bx],BLOCK_IMAGES[game.current_piece]);
lv_obj_clear_flag(ui.block_imgs[by][bx],LV_OBJ_FLAG_HIDDEN);
}
}
}
}
// 更新分数、等级、行数显示
char score_str[20];
sprintf(score_str,"score:%lu",game.score);
lv_label_set_text(ui.score_label,score_str);
char level_str[20];
int current_speed=game.lines/10+1;
sprintf(level_str,"speed:%d",current_speed);
lv_label_set_text(ui.level_label,level_str);
char lines_str[20];
sprintf(lines_str,"lines:%u",game.lines);
lv_label_set_text(ui.lines_label,lines_str);
update_next_preview();
}
//旋转当前的方块
void rotate_piece()
{
int new_rotation = (game.rotation + 1) % 4;
// 尝试旋转,如果碰撞则尝试左右微调
for (int offset = 0; offset <= 2; offset++) {
if (!check_collision(game.x + offset, game.y, new_rotation)) {
game.x += offset;
game.rotation = new_rotation;
return;
}
if (!check_collision(game.x - offset, game.y, new_rotation)) {
game.x -= offset;
game.rotation = new_rotation;
return;
}
}
// 尝试上下微调(针对I型方块)
if (game.current_piece == 2) {
if (!check_collision(game.x, game.y + 1, new_rotation)) {
game.y += 1;
game.rotation = new_rotation;
return;
}
}
}
void create_ui()
{
//主游戏区
ui.game_area=lv_obj_create(lv_screen_active());
lv_obj_set_size(ui.game_area,11*BLOCK_SIZE,21*BLOCK_SIZE);
lv_obj_align(ui.game_area,LV_ALIGN_LEFT_MID,10,0);
lv_obj_set_style_bg_color(ui.game_area,lv_color_hex(0xC0C0C0),0);
lv_obj_set_style_bg_opa(ui.game_area, LV_OPA_COVER, 0);
lv_obj_clear_flag(ui.game_area, LV_OBJ_FLAG_SCROLLABLE);
// 标题
lv_obj_t *lab = lv_label_create(lv_screen_active());
lv_obj_set_size(lab, 400, 200);
lv_obj_set_pos(lab, 400, 40);
lv_label_set_text(lab, "俄罗斯方块");
static lv_style_t lab_style;
lv_style_init(&lab_style);
lv_style_set_bg_color(&lab_style, lv_color_hex(0x7300FD));
lv_obj_set_style_text_align(lab, LV_TEXT_ALIGN_CENTER, LV_STATE_DEFAULT);
lv_style_set_opa(&lab_style, 255);
lv_style_set_border_color(&lab_style, lv_color_hex(0xFF0000));
lv_style_set_border_width(&lab_style, 5);
lv_style_set_border_opa(&lab_style, 255);
lv_style_set_radius(&lab_style, 10);
lv_style_set_text_color(&lab_style, lv_color_hex(0xFF0000));
lv_style_set_text_font(&lab_style, &lv_my_font);
lv_obj_add_style(lab, &lab_style, LV_STATE_DEFAULT);
// 背景图
lv_obj_t *img = lv_img_create(lv_scr_act());
lv_img_set_src(img, "A:wang.bmp");
lv_obj_set_pos(img,30,0);
lv_obj_set_style_opa(img, 50, 0);
// 右侧信息面板
lv_obj_t *panel=lv_obj_create(lv_screen_active());
lv_obj_set_size(panel,150,LV_PCT(100));
lv_obj_align(panel,LV_ALIGN_RIGHT_MID,0,0);
lv_obj_clear_flag(panel,LV_OBJ_FLAG_SCROLLABLE);
//分数
ui.score_label=lv_label_create(panel);
lv_label_set_text(ui.score_label,"score:0");
lv_obj_set_style_text_font(ui.score_label,&lv_font_montserrat_20,0);
lv_obj_set_size(ui.score_label, 100, 60);
lv_obj_set_pos(ui.score_label, 5, 30);
//下一个方块预览
lv_obj_t *next_label=lv_label_create(panel);
lv_label_set_text(next_label,"next:");
lv_obj_set_style_text_font(next_label,&lv_font_montserrat_20,0);
lv_obj_set_size(next_label, 60, 80);
lv_obj_set_pos(next_label, 5, 120);
ui.next_block=lv_img_create(panel);
lv_img_set_src(ui.next_block,"A:L.bmp");
lv_obj_set_pos(ui.next_block, 5, 160);
//速度
ui.level_label=lv_label_create(panel);
lv_label_set_text(ui.level_label,"speed:1");
lv_obj_set_style_text_font(ui.level_label,&lv_font_montserrat_20,0);
lv_obj_set_size(ui.level_label, 80, 60);
lv_obj_set_pos(ui.level_label, 5, 400);
//行数
ui.lines_label=lv_label_create(panel);
lv_label_set_text(ui.lines_label,"lines:0");
lv_obj_set_style_text_font(ui.lines_label,&lv_font_montserrat_20,0);
lv_obj_set_size(ui.lines_label, 60, 60);
lv_obj_set_pos(ui.lines_label, 5, 500);
// 初始化方块显示对象
for(int y=0;y<20;y++)
{
for(int x=0;x<10;x++)
{
ui.block_imgs[y][x]=lv_img_create(ui.game_area);
lv_obj_set_size(ui.block_imgs[y][x],BLOCK_SIZE,BLOCK_SIZE);
lv_obj_set_pos(ui.block_imgs[y][x],x*BLOCK_SIZE,y*BLOCK_SIZE);
lv_obj_add_flag(ui.block_imgs[y][x],LV_OBJ_FLAG_HIDDEN);
}
}
// 创建控制按钮(只创建一次)
lv_obj_t *but1=my_lv_init_button(lv_screen_active(),440,370,100,100,0x2691FA,0x000A03,"left");
lv_obj_add_event_cb(but1, my_but1_event_cb, LV_EVENT_CLICKED, NULL);
lv_obj_t *but2=my_lv_init_button(lv_screen_active(),640,370,100,100,0x2691FA,0x000A03,"right");
lv_obj_add_event_cb(but2, my_but2_event_cb, LV_EVENT_CLICKED, NULL);
lv_obj_t *but3=my_lv_init_button(lv_screen_active(),540,270,100,100,0x2691FA,0x000A03,"full");
lv_obj_add_event_cb(but3, my_but3_event_cb, LV_EVENT_CLICKED, NULL);
lv_obj_t *but4=my_lv_init_button(lv_screen_active(),530,470,120,100,0x2691FA,0x000A03,"rotate");
lv_obj_add_event_cb(but4, my_but4_event_cb, LV_EVENT_CLICKED, NULL);
}
//检查方块状态
bool check_collision(int new_x, int new_y, int new_rotation)
{
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
// 根据旋转状态获取方块的形状
int block_value;
switch (new_rotation % 4) {
case 0:
block_value = THTROMINOS[game.current_piece][y][x];
break;
case 1:
block_value = THTROMINOS[game.current_piece][x][3 - y];
break; // 右转90°
case 2:
block_value = THTROMINOS[game.current_piece][3 - y][3 - x];
break; // 180°
case 3:
block_value = THTROMINOS[game.current_piece][3 - x][y];
break; // 左转90°
}
if (block_value) {
int bx = new_x + x;
int by = new_y + y;
// 允许部分方块在顶部外(by < 0)
if (bx < 0 || bx >= 10 || by >= 20) {
return true;
}
if (by >= 0 && game.board[by][bx] != EMPTY) {
return true;
}
}
}
}
return false;
}
//计算方块的实际坐标
int get_block_pos(int* bx, int* by, int x, int y, int rotation, int piece_type)
{
int offset_x = 0, offset_y = 0;
// I型方块特殊处理
if (piece_type == 2) { // I型
if (rotation % 2 == 1) { // 竖向
offset_x = -1; // 向左补偿1格
offset_y = -1; // 向上补偿1格
}
}
// 通用坐标转换
switch (rotation & 3) {
case 0: *bx = x; *by = y; break;
case 1: *bx = game.x + (3 - (y - game.y)); *by = game.y + (x - game.x); break;
case 2: *bx = game.x + (3 - (x - game.x)); *by = game.y + (3 - (y - game.y)); break;
case 3: *bx = game.x + (y - game.y); *by = game.y + (3 - (x - game.x)); break;
}
return (*bx >= 0 && *bx < 10 && *by >= 0 && *by < 20);
}
//锁住方块(当方块触地或者接触到其他已经固定好的方块时)
void lock_piece()
{
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
int block_value = THTROMINOS[game.current_piece][y][x];
if (block_value) {
int bx = game.x + x;
int by = game.y + y;
if (by < 0) { // 如果有部分方块在顶部外,不允许锁定
return;
}
}
}
}
for(int y=0;y<4;y++)
{
for(int x=0;x<4;x++)
{
int block_value;
switch (game.rotation % 4) {
case 0: block_value = THTROMINOS[game.current_piece][y][x]; break;
case 1: block_value = THTROMINOS[game.current_piece][x][3 - y]; break; // 右转90°
case 2: block_value = THTROMINOS[game.current_piece][3 - y][3 - x]; break; // 180°
case 3: block_value = THTROMINOS[game.current_piece][3 - x][y]; break; // 左转90°
}
if (block_value) {
int bx = game.x + x;
int by = game.y + y;
if (by >= 0 && by < 20 && bx >= 0 && bx < 10) {
game.board[by][bx] = game.current_piece;
}
}
}
}
}
//清除满了格子的一行
void clear_lines()
{
int lines_cleared=0;
for(int y=19;y>=0;y--)
{
bool line_full=true;
for(int x=0;x<10;x++)
{
if(game.board[y][x]==EMPTY)
{
line_full=false;
break;
}
}
//如果下面的方块满了(消除)
if(line_full)
{
lines_cleared++;
for(int ny=y;ny>0;ny--)
{
memcpy(game.board[ny],game.board[ny-1],sizeof(game.board[0]));
}
//清除最顶行
memset(game.board[0],EMPTY,sizeof(game.board[0]));
y++;
}
}
if(lines_cleared>0)
{
//加分数
game.score+=lines_cleared*lines_cleared*100;
//加行数
game.lines+=lines_cleared;
game.level=(game.lines/10)+1;
//游戏下落的速度(值越小则越快)
game.fall_speed=1000-(game.level-1)*100;
if(game.fall_speed<100)
{
game.fall_speed=100;
}
}
}
void update_next_preview()
{
if(game.next_piece>=0&&game.next_piece<7)
{
lv_img_set_src(ui.next_block,BLOCK_IMAGES[game.next_piece]);
}
else
{
lv_img_set_src(ui.next_block,"A:1.bmp");
}
}
//交接下一个方块并且判断游戏是否结束
void spawn_new_piece()
{
game.current_piece=game.next_piece;
game.next_piece=get_next_from_bag();
game.x=(game.current_piece==2)?3:4;
game.y=(game.current_piece==2)?-2:-1;
game.rotation=0;
update_next_preview();
if(check_collision(game.x,game.y,game.rotation))
{
if (!check_collision(game.x+1, game.y, game.rotation)) {
game.x++;
} else {
//游戏结束
printf("GAME OVER!\n");
game_over = true;
}
}
}
//移动方块
bool move_piece(int dx,int dy)
{
if(!check_collision(game.x+dx,game.y+dy,game.rotation))
{
game.x+=dx;
game.y+=dy;
return true;
}
return false;
}
//左键
static void my_but1_event_cb(lv_event_t *e)
{
pthread_mutex_lock(&game_mutex);
move_piece(-1,0);
pthread_mutex_unlock(&game_mutex);
}
//右键
static void my_but2_event_cb(lv_event_t *e)
{
pthread_mutex_lock(&game_mutex);
move_piece(1,0);
pthread_mutex_unlock(&game_mutex);
}
//快速落键
static void my_but3_event_cb(lv_event_t *e)
{
pthread_mutex_lock(&game_mutex);
while(1) {
if (!move_piece(0, 1)) {
// 检查是否可以锁定
bool can_lock = true;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
if (THTROMINOS[game.current_piece][y][x] &&
(game.y + y) < 0) {
can_lock = false;
break;
}
}
if(!can_lock) break;
}
if (can_lock) {
lock_piece();
clear_lines();
spawn_new_piece();
}
break;
}
}
pthread_mutex_unlock(&game_mutex);
}
//旋转键
static void my_but4_event_cb(lv_event_t *e)
{
pthread_mutex_lock(&game_mutex);
rotate_piece();//旋转
pthread_mutex_unlock(&game_mutex);
}
|
2301_80220293/00VScodeDebug04testc05
|
main.c
|
C
|
unknown
| 22,146
|
#include "lvgl/lvgl.h"
const uint8_t mouse_cursor_icon_map[] = {
0x19, 0x19, 0x19, 0xb8, 0x1e, 0x1e, 0x1e, 0xc8, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x48, 0x48, 0xcc, 0xb2, 0xb2, 0xb2, 0xff, 0x3a, 0x3a, 0x3a, 0xcc, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x0a, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x3b, 0x3b, 0x3b, 0xc8, 0xf6, 0xf6, 0xf6, 0xff, 0xdc, 0xdc, 0xdc, 0xff, 0x43, 0x43, 0x43, 0xe0, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x0a, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x3b, 0x3b, 0x3b, 0xcb, 0xe6, 0xe6, 0xe6, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xe5, 0xe5, 0xe5, 0xff, 0x59, 0x59, 0x59, 0xf3, 0x00, 0x00, 0x00, 0x4f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x3c, 0x3c, 0x3c, 0xcb, 0xe9, 0xe9, 0xe9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf5, 0xf5, 0xf5, 0xff, 0x72, 0x72, 0x72, 0xff, 0x00, 0x00, 0x00, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x3d, 0x3d, 0x3d, 0xcb, 0xe9, 0xe9, 0xe9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x8a, 0x8a, 0x8a, 0xff, 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x99, 0x99, 0x99, 0x00, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x3e, 0x3e, 0x3e, 0xcb, 0xe9, 0xe9, 0xe9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa2, 0xa2, 0xa2, 0xff, 0x13, 0x13, 0x13, 0xab, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x3f, 0x3f, 0x3f, 0xcb, 0xe9, 0xe9, 0xe9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb7, 0xb7, 0xb7, 0xff, 0x1f, 0x1f, 0x1f, 0xbb, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x41, 0x41, 0x41, 0xcc, 0xea, 0xea, 0xea, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xca, 0xca, 0xca, 0xff, 0x3d, 0x3d, 0x3d, 0xd8, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x41, 0x41, 0x41, 0xcc, 0xea, 0xea, 0xea, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xde, 0xde, 0xde, 0xff, 0x56, 0x56, 0x56, 0xef, 0x00, 0x00, 0x00, 0x4f, 0x00, 0x00, 0x00, 0x00,
0x42, 0x42, 0x42, 0xcc, 0xea, 0xea, 0xea, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf3, 0xf3, 0xf3, 0xff, 0x76, 0x76, 0x76, 0xff, 0x00, 0x00, 0x00, 0x6b,
0x43, 0x43, 0x43, 0xcc, 0xea, 0xea, 0xea, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xce, 0xce, 0xce, 0xff, 0x80, 0x80, 0x80, 0xf7, 0x74, 0x74, 0x74, 0xf8, 0x6d, 0x6d, 0x6d, 0xfb, 0x72, 0x72, 0x72, 0xf8, 0x57, 0x57, 0x57, 0xff, 0x0c, 0x0c, 0x0c, 0xb3,
0x44, 0x44, 0x44, 0xcc, 0xeb, 0xeb, 0xeb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xfb, 0xfb, 0xfb, 0xff, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0xc9, 0xc9, 0xff, 0x13, 0x13, 0x13, 0xb7, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x0c, 0x29, 0x29, 0x29, 0x07,
0x45, 0x45, 0x45, 0xcc, 0xe8, 0xe8, 0xe8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xd9, 0xd9, 0xd9, 0xff, 0x5e, 0x5e, 0x5e, 0xff, 0xe2, 0xe2, 0xe2, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x62, 0x62, 0xf0, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x45, 0x45, 0x45, 0xcc, 0xf9, 0xf9, 0xf9, 0xff, 0xec, 0xec, 0xec, 0xff, 0x4a, 0x4a, 0x4a, 0xd8, 0x00, 0x00, 0x00, 0x78, 0x8a, 0x8a, 0x8a, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc3, 0xc3, 0xc3, 0xff, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x58, 0x58, 0x58, 0xd3, 0xd9, 0xd9, 0xd9, 0xff, 0x5e, 0x5e, 0x5e, 0xef, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x00, 0x3b, 0x3b, 0x3b, 0xc7, 0xe9, 0xe9, 0xe9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf4, 0xf4, 0xf4, 0xff, 0x54, 0x54, 0x54, 0xdc, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00,
0x3e, 0x3e, 0x3e, 0xe0, 0x54, 0x54, 0x54, 0xff, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x8e, 0x8e, 0x8e, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb0, 0xb0, 0xb0, 0xff, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x0c, 0x0c, 0x04, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, 0x4f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x4c, 0x4c, 0x4c, 0xd0, 0xec, 0xec, 0xec, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xf4, 0xf4, 0xf4, 0xff, 0x53, 0x53, 0x53, 0xd8, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x1e, 0x1e, 0x00, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xab, 0xab, 0xab, 0xff, 0xf6, 0xf6, 0xf6, 0xff, 0x80, 0x80, 0x80, 0xff, 0x31, 0x31, 0x31, 0xac, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x09, 0x09, 0x09, 0x03, 0x02, 0x02, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x2e, 0x2e, 0x2e, 0xd7, 0x38, 0x38, 0x38, 0xc7, 0x00, 0x00, 0x00, 0x47, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
lv_image_dsc_t mouse_cursor_icon = {
.header.magic = LV_IMAGE_HEADER_MAGIC,
.header.w = 14,
.header.h = 20,
.data_size = 280 * 4,
.header.cf = LV_COLOR_FORMAT_ARGB8888,
.data = mouse_cursor_icon_map,
};
|
2301_80220293/00VScodeDebug04testc05
|
mouse_cursor_icon.c
|
C
|
unknown
| 7,097
|
from pygame import *
import random
num = random.randint(10,100)
print(num)
num2 = random.random()
print(num2)
print('hello world')
print("hello world")
print('''hello world''')
for i in range(10):
print(i)
|
2301_80211016/python
|
0918.py
|
Python
|
unknown
| 217
|
if 2>1:
print("hello world")
else:
print("hello world")
print("hello world")
print("hello world"+"hello world"+"hello world"
+"hello world"+"hello world"+"hello world")
# print("hello world"+"hello world"+"hello world")
# print("hello world"+"hello world"+"hello world")
# print("hello world"+"hello world"+"hello world")
num = 10
print(type(num))
num = "hello world"
print(type(num))
year = input("请输入一个年份")
print(year)
print(type(year))
year = int(input("请输入一个年份"))
print(type(year))
str1 = 'h'
str2 = 'l'
str3 = 'm'
print(str1,str2,str3,sep='-',end='\t')
|
2301_80211016/python
|
0925/0925.py
|
Python
|
unknown
| 613
|
price_list={
"金士顿U盘8G":40,
"胜创16G7F卡":50,
"读卡器":8,
"网线2米":5
}
num_list = {
"金士顿U盘8G":1,
"胜创16G7F卡":1,
"读卡器":1,
"网线2米":1
}
print('............................................')
print("单号: DH202301010011")
print("时间: 2023-01-01 08:56:15")
print('............................................')
print("名称 数量 单价 金额")
print("金士顿U盘8G"," ",num_list.get("金士顿U盘8G")," ",price_list.get("金士顿U盘8G"), " ",num_list.get("金士顿U盘8G")*price_list.get("金士顿U盘8G"))
print("胜创16G7F卡"," ",num_list.get("胜创16G7F卡")," ",price_list.get("胜创16G7F卡"), " ",num_list.get("胜创16G7F卡")*price_list.get("胜创16G7F卡"))
print("读卡器"," ",num_list.get("读卡器")," ",price_list.get("读卡器"), " ",num_list.get("读卡器")*price_list.get("读卡器"))
print("网线2米"," ",num_list.get("网线2米")," ",price_list.get("网线2米"), " ",num_list.get("网线2米")*price_list.get("网线2米"))
print('............................................')
print("总数:4"," ","总额:103")
print("折后总额:103", " ","找零:0")
print("收银:管理员")
print('............................................')
|
2301_80211016/python
|
0925/0925_2.py
|
Python
|
unknown
| 1,371
|
name = input("请输入你的姓名:")
height = float(input("请输入你的身高(m):"))
weight = float(input("请输入你的体重(kg):"))
BMI = weight / pow(height, 2)
print(f'BMI值为:{round(BMI, 2)}')
if BMI < 18.5:
print("偏瘦")
else:
if 18.5 < BMI < 25:
print("正常")
else:
if 25 <= BMI < 28:
print("偏胖")
else:
if 28 <= BMI < 32:
print("肥胖")
else:
print("严重肥胖")
|
2301_80211016/python
|
0925/0925_3.py
|
Python
|
unknown
| 511
|
#流程控制
S = int(input())
M = int(input())
if M>=1000:
if S>=10000:
print("您是钻石会员")
elif 500<M<1000:
if 10000>S>=5000:
print("您是白金会员")
elif 200<=M<500:
if 2000<=S<5000:
print("您是黄金会员")
elif 100<=M<200:
if 1000<=S<2000:
print("您是白银会员")
elif 500<=M<1000:
print("您是青铜会员")
elif M<500:
print("您是普通会员")
|
2301_80211016/python
|
1009/1009_1.py
|
Python
|
unknown
| 430
|
# 输出1000以内的水仙花数
for num in range(100, 1000):
# 分解各位数字
a = num // 100 # 百位
b = num // 10 % 10 # 十位
c = num % 10 # 个位
# 判断是否为水仙花数
if a ** 3 + b ** 3 + c ** 3 == num:
print(num)
|
2301_80211016/python
|
1009/1009_2.py
|
Python
|
unknown
| 272
|
# 打印九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j}", end="\t")
print()
|
2301_80211016/python
|
1009/1009_3.py
|
Python
|
unknown
| 131
|
list = [1,2,3,4,5]
print(list)
for i in list:
print(i,end=" ")
print(list[0])
print(list[-1])
print(list[2:])
print(list[::2])
print(list[:3])
print(list[::-1])
list.append(6)
print(list)
list.insert(0,0)
print(list)
list.extend([7,8])
print(list)
list2 = [11,5,33,22,66,1,9]
list2.sort()
print(list2)
list2.sort(reverse=True)
print(list2)
list2_new = sorted(list2)
print(list2)
print(list2_new)
list.pop()
print(list)
list.pop(2)
print(list)
list.remove(5)
print(list)
list[0]= 1
print(list)
list3 = [i for i in list if i % 2 == 0]
print(list3)
tuple = (1,2,3,4,5)
print(tuple)
for item in tuple:
print(i,end=" ")
print(tuple)
print(tuple[0])
print(tuple[-1])
print(tuple[1:4])
print(tuple[-2:])
print(tuple[:2])
print(tuple[::2])
set1 = set([1,2,3,4,5,3,7,4,1])
print(set1)
set1.pop()
print(set1)
set1.remove(5)
print(set1)
#字典
dict0 = {}
dict1 = dict()
dict2 = {'name':'zhangsan','age':18,'sex':'男'}
print(dict2)
print(dict2['name'])
print(dict2['age'])
for key,value in dict2.items():
print(key, value)
for key in dict2.keys():
print(key)
print(dict2.get('id','没有相关数据'))
print(dict2.get('id2'))#返回None
#添加
dict2['id'] = 100#上面不存在id,添加id
print(dict2)
dict2['id'] = 101#上面存在id,就修改id
print(dict2)
dict2.update({'id':'102','sex':'女'})
print(dict2)
dict2.update({'phone':'12345678901','email':'<EMAIL>'})
print(dict2)
#删除
dict2.pop('id')
print(dict2)
item = dict2.popitem()
print(type(item))
print(dict2)
dict2.clear()
print(dict2)
|
2301_80211016/python
|
1016/1016_test.py
|
Python
|
unknown
| 1,532
|
#函数
sum=0 #全局变量
# print(summmmm) #报错name 'summmmm' is not defined
def add(a,b):
# print(sum)
global sum
sum=sum+1 #没有上述声明global则会报错cannot access local variable 'sum' where it is not associated with a value
print(sum)
print('-------------')
num=100 #局部变量
num=num+1
# sub(a,b)
#下面这个不推荐使用
# def mul(a,b):
# return a*b
return a+b,a*a+b*b
def sub(a,b):
return a-b
# result = add(b=10,a=20)
result = add(10,20)
# result = add(10,b=20)
print(result)
#斐波那契
def fib(n):
if n<=2:
return 1
return fib(n-1) + fib(n-2)
print(fib(10))
for i in range(1,10+1):
print(fib(i),end=' ')
|
2301_80211016/python
|
1023/1023_1.py
|
Python
|
unknown
| 720
|
#file = open("student.txt", "r", encoding="utf-8")
#print(file.read())
#file.close()
import os
#with open('student.txt', 'r', encoding='utf-8') as file:
#print(file.read())
#print(file.readline().strip())
#while True:
#line = file.readline()
# if not line:
# break
# print(line.strip())
#list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8']
#with open('student.txt', 'w', encoding='utf-8') as file:
# file.write('hello word')
# file.writelines(list)
#with open('./a.png', 'rb') as file:
# with open('C:\\Users\\GXH59\\Pictures\\VRChat\\2024-08\\a.png','wb')as file2:
# while True:
# date = file.read(1024)
# if not date:
# break
# file2.write(date)
#for root,dirs,files in os.walk('./'):
# print(files)
# print(root)
|
2301_80211016/python
|
1106/1106_1.py
|
Python
|
unknown
| 847
|
from entity import User
user1 = User()
user1.show()
print(user1.count)
#print(User.count)
user2 = User()
User.show1()
User.show2()
user2.show1()
user2.show2()
from entity import User,Child,Person
# user1=User()
# user1.show()
# print(user1.count)
user2 = User("admin","18","male","111111@qq.com")
print(User.count) #私有属性无法直接访问
User.count = 100
print(user2.count)
user2.phone = "111111"
user3 = User("Root","18","male","222222@qq.cm")
user3.show()
#User.show() #类名不可调用实列方法
print("______________________")
User.show1()
#User.show2()
user4=User()
user5=User("ry")
user6=User("ry","18")
user7=User("ry","18","male")
user8=User("ry","18","male","ry@ryqq.com")
user5.setname("ry9999")
print(user5.getname())
print("_____________11_________")
child1=Child()
child1.show()
child1.study()
print(child1.name)
print(child1.age)
print(child1.age)
|
2301_80211016/python
|
1113/1113_1.py
|
Python
|
unknown
| 892
|
class User:
count = 0
def show(self):
print("show---------")
@classmethod
def show1(cls):
print("show1---------")
@staticmethod
def show2():
print("show2---------")
def __init__(self,name=None,age=None,sex=None,email=None):
#成员变量
self.__name = name
self.age = age
self.sex = sex
self.email = email
def getname(self):
return self.__name
def setname(self,name):
self.__name = name
def show(self):
print("show------------")
@classmethod
def show1(cls):
print("show------------")
@staticmethod
def __show2():
print("show------------")
class Person:
name = "parent"
def show(self):
print(f"show------{self.name}------")
class Child(Person):
age = 18
def study(self):
print(f"study-------{self.age}------")
def show(self):
print(f"child------{self.name}------")
|
2301_80211016/python
|
1113/entity.py
|
Python
|
unknown
| 978
|
import re
import tkinter as tk
from bdb import checkfuncname
from tkinter import messagebox
#创建主窗体
root = tk.Tk()
root.title("登录")
#获取设备宽和高
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
window_width = 500
window_height = 300
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
root.geometry(f"{window_width}x{window_height}+{x}+{y}")
root.config(pady=50)
#创建按钮
# login_btn1 = tk.Button(root,text="登录",width=20)
# login_btn1.grid(row=0, column=0)
# login_btn2 = tk.Button(root,text="登录",width=20)
# login_btn2.grid(row=0, column=1)
# login_btn3 = tk.Button(root,text="登录",width=20)
# login_btn3.grid(row=1, column=0)
# login_btn4 = tk.Button(root,text="登录",width=20)
# login_btn4.grid(row=1, column=1)
tk.Label(root,text="用户名",width=27,anchor="e").grid(row=0, column=0)
username = tk.Entry(root,width=20,validate="focusout",validatecommand=lambda : checkUserName())
username.grid(row=0, column=1)
username.grid(row=0, column=1)
lbl_username = tk.Label(root,text="",width=15,bg="red")
lbl_username.grid(row=0, column=2)
tk.Label(root,text="",width=27,anchor="e").grid(row=1, column=0)
tk.Label(root,text="密码",width=27,anchor="e").grid(row=2, column=0)
pwd = tk.Entry(root,width=20)
pwd.grid(row=2, column=1)
lbl_pwd = tk.Label(root,text="",width=15,bg="red")
lbl_pwd.grid(row=2, column=2)
tk.Label(root,text="",width=27,anchor="e").grid(row=3, column=0)
login_btn = tk.Button(root,text="登录",width=10,command=lambda:login())
login_btn.grid(row=4, column=1)
logout_btn = tk.Button(root,text="退出",width=10,command=lambda:logout())
logout_btn.grid(row=4, column=2)
def login():
str_name = username.get().strip()
str_pwd = pwd.get().strip()
if str_name == "admin" and str_pwd == "123456":
messagebox.showinfo("提示","登录成功")
else:
messagebox.showwarning("提示","用户名或密码错误")
def logout():
result = messagebox.askokcancel("提示","确定要退出吗")
if result:
root.quit()
else:
pass
def checkUserName():
name = username.get().strip()
# 用户名为空,跳过验证
if not name:
return True
else:
# 判断用户名格式
if not re.match(r'^[a-zA-Z0-9_-]{4,16}$', username):
lbl_username.config(text='用户名格式不正确', fg='white')
return False # 验证失败返回False
else:
lbl_username.config(text='')
return True
root.mainloop()
root.mainloop()
|
2301_80211016/python
|
1127/login.py
|
Python
|
unknown
| 2,596
|
# 这是一个示例 Python 脚本。
# 按 Shift+F10 执行或将其替换为您的代码。
# 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。
def print_hi(name):
# 在下面的代码行中使用断点来调试脚本。
print(f'Hi, {name}') # 按 Ctrl+F8 切换断点。
print(f'Hi, {name}') # 按 Ctrl+F8 切换断点。
# 按装订区域中的绿色按钮以运行脚本。
if __name__ == '__main__':
print_hi('PyCharm')
# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
|
2301_80211016/python
|
main.py
|
Python
|
unknown
| 558
|
# 学生管理系统
students = {} # 用字典存储学生信息,键为学号,值为学生信息元组
def insert_student():
"""添加学生"""
student_id = input("请输入学号: ")
if student_id in students:
print("该学号已存在!")
return
name = input("请输入姓名: ")
age = input("请输入年龄: ")
grade = input("请输入班级: ")
# 使用元组存储学生信息
student_info = (name, age, grade)
students[student_id] = student_info
print(f"学生 {name} 添加成功!")
def delete_student():
"""删除学生"""
id = input("请输入学生id : ")
if id in students:
url = input("是否删除",students[id][0],"y或n")
if url == "y":
del students[id]
print(students[id][0],"删除成功")
elif url == "n":
print(students[id][0],"未删除")
return
return
def update_student():
"""修改学生信息"""
id = input("请输入学生id : ")
if id in students:
url = input("是否修改", students[id][0], "y或n")
if url == "y":
name = input("请输入姓名: ")
age = input("请输入年龄: ")
grade = input("请输入班级: ")
student_info = (name, age, grade)
students[id] = student_info
print(f"学生 {name} 修改成功!")
elif url == "n":
print(students[id][0], "未修改")
return
return
def select_student():
"""查询学生信息"""
id = input("请输入学生编号: ")
name = input("请输入要查询的学生姓名: ")
if id in students and students[id][0] == name:
print(f"学号: {id}, 姓名: {students[id][0]}, 年龄: {students[id][1]}, 班级: {students[id][2]}")
return
else:
print("查无此人,请检查后重新输入")
return
def display_all_students():
"""显示所有学生"""
if not students:
print("暂无学生信息!")
return
print("\n所有学生信息:")
print("-" * 40)
for student_id, student_info in students.items():
print(f"学号: {student_id}, 姓名: {student_info[0]}, 年龄: {student_info[1]}, 班级: {student_info[2]}")
print("-" * 40)
def main():
"""主函数"""
while True:
print("\n===== 学生管理系统 =====")
print("1. 添加学生")
print("2. 删除学生")
print("3. 修改学生信息")
print("4. 查询学生信息")
print("5. 显示所有学生")
print("0. 退出系统")
choice = input("请选择操作: ")
if choice == '1':
insert_student()
elif choice == '2':
delete_student()
elif choice == '3':
update_student()
elif choice == '4':
select_student()
elif choice == '5':
display_all_students()
elif choice == '0':
print("感谢使用学生管理系统!")
break
else:
print("无效选择,请重新输入!")
# 启动系统
if __name__ == "__main__":
main()
|
2301_80211016/python
|
学生管理系统/App.py
|
Python
|
unknown
| 3,184
|
#用对象存储信息 使用面向对象存储信息
#开户 查询 锁定 解锁 转账 退出 存款 取款
class Account:
def __init__(self, name, id_number, password, balance=0):
self.name = name
self.id_number = id_number
self.password = password
self.balance = balance
self.locked = False
def deposit(self, amount):
if self.locked:
return False, "账户已锁定,无法存款"
self.balance += amount
return True, f"存款成功,当前余额:{self.balance}"
def withdraw(self, amount):
if self.locked:
return False, "账户已锁定,无法取款"
if amount > self.balance:
return False, "余额不足"
self.balance -= amount
return True, f"取款成功,当前余额:{self.balance}"
def show_info(self):
lock_state = "锁定" if self.locked else "正常"
return f"姓名: {self.name}, 身份证: {self.id_number}, 余额: {self.balance}, 状态: {lock_state}"
class Bank:
def __init__(self):
self.accounts = {}
def create_account(self):
name = input("请输入姓名:")
id_number = input("请输入身份证号:")
password = input("请输入密码:")
if id_number in self.accounts:
print("该身份证已开户")
return
self.accounts[id_number] = Account(name, id_number, password)
print("开户成功!")
def query(self):
id_number, account = self._login()
if account:
print(account.show_info())
def deposit(self):
id_number, account = self._login()
if account:
amount = float(input("请输入存款金额:"))
ok, msg = account.deposit(amount)
print(msg)
def withdraw(self):
id_number, account = self._login()
if account:
amount = float(input("请输入取款金额:"))
ok, msg = account.withdraw(amount)
print(msg)
def lock(self):
id_number = input("请输入要锁定的身份证号:")
if id_number in self.accounts:
self.accounts[id_number].locked = True
print("账户已锁定")
else:
print("无此账户")
def unlock(self):
id_number = input("请输入要解锁的身份证号:")
if id_number in self.accounts:
self.accounts[id_number].locked = False
print("账户已解锁")
else:
print("无此账户")
def transfer(self):
print("=== 转账操作 ===")
from_id, from_acc = self._login()
if not from_acc:
return
to_id = input("请输入收款人身份证号:")
if to_id not in self.accounts:
print("收款账户不存在")
return
amount = float(input("请输入转账金额:"))
ok, msg = from_acc.withdraw(amount)
if not ok:
print(msg)
return
self.accounts[to_id].deposit(amount)
print("转账成功")
def _login(self):
id_number = input("请输入身份证号:")
if id_number not in self.accounts:
print("无此账户")
return None, None
account = self.accounts[id_number]
if account.locked:
print("账户已锁定")
return None, None
password = input("请输入密码:")
if password != account.password:
print("密码错误")
return None, None
return id_number, account
def run(self):
while True:
print("\n==== 银行系统 ====")
print("1. 开户")
print("2. 查询")
print("3. 锁定账户")
print("4. 解锁账户")
print("5. 转账")
print("6. 存款")
print("7. 取款")
print("8. 退出系统")
choice = input("请选择功能:")
if choice == "1":
self.create_account()
elif choice == "2":
self.query()
elif choice == "3":
self.lock()
elif choice == "4":
self.unlock()
elif choice == "5":
self.transfer()
elif choice == "6":
self.deposit()
elif choice == "7":
self.withdraw()
elif choice == "8":
print("已退出系统")
break
else:
print("输入错误,请重新选择")
if __name__ == '__main__':
bank = Bank()
bank.run()
|
2301_80211016/python
|
银行管理系统/main.py
|
Python
|
unknown
| 4,717
|
package com.sky.constant;
/**
* 公共字段自动填充相关常量
*/
public class AutoFillConstant {
/**
* 实体类中的方法名称
*/
public static final String SET_CREATE_TIME = "setCreateTime";
public static final String SET_UPDATE_TIME = "setUpdateTime";
public static final String SET_CREATE_USER = "setCreateUser";
public static final String SET_UPDATE_USER = "setUpdateUser";
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/constant/AutoFillConstant.java
|
Java
|
unknown
| 424
|
package com.sky.constant;
public class JwtClaimsConstant {
public static final String EMP_ID = "empId";
public static final String USER_ID = "userId";
public static final String PHONE = "phone";
public static final String USERNAME = "username";
public static final String NAME = "name";
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/constant/JwtClaimsConstant.java
|
Java
|
unknown
| 312
|
package com.sky.constant;
/**
* 信息提示常量类
*/
public class MessageConstant {
public static final String PASSWORD_ERROR = "密码错误";
public static final String ACCOUNT_NOT_FOUND = "账号不存在";
public static final String ACCOUNT_LOCKED = "账号被锁定";
public static final String UNKNOWN_ERROR = "未知错误";
public static final String USER_NOT_LOGIN = "用户未登录";
public static final String CATEGORY_BE_RELATED_BY_SETMEAL = "当前分类关联了套餐,不能删除";
public static final String CATEGORY_BE_RELATED_BY_DISH = "当前分类关联了菜品,不能删除";
public static final String SHOPPING_CART_IS_NULL = "购物车数据为空,不能下单";
public static final String ADDRESS_BOOK_IS_NULL = "用户地址为空,不能下单";
public static final String LOGIN_FAILED = "登录失败";
public static final String UPLOAD_FAILED = "文件上传失败";
public static final String SETMEAL_ENABLE_FAILED = "套餐内包含未启售菜品,无法启售";
public static final String PASSWORD_EDIT_FAILED = "密码修改失败";
public static final String DISH_ON_SALE = "起售中的菜品不能删除";
public static final String SETMEAL_ON_SALE = "起售中的套餐不能删除";
public static final String DISH_BE_RELATED_BY_SETMEAL = "当前菜品关联了套餐,不能删除";
public static final String ORDER_STATUS_ERROR = "订单状态错误";
public static final String ORDER_NOT_FOUND = "订单不存在";
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/constant/MessageConstant.java
|
Java
|
unknown
| 1,545
|
package com.sky.constant;
/**
* 密码常量
*/
public class PasswordConstant {
public static final String DEFAULT_PASSWORD = "123456";
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/constant/PasswordConstant.java
|
Java
|
unknown
| 147
|
package com.sky.constant;
/**
* 状态常量,启用或者禁用
*/
public class StatusConstant {
//启用
public static final Integer ENABLE = 1;
//禁用
public static final Integer DISABLE = 0;
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/constant/StatusConstant.java
|
Java
|
unknown
| 221
|
package com.sky.context;
public class BaseContext {
public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
public static void setCurrentId(Long id) {
threadLocal.set(id);
}
public static Long getCurrentId() {
return threadLocal.get();
}
public static void removeCurrentId() {
threadLocal.remove();
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/context/BaseContext.java
|
Java
|
unknown
| 372
|
package com.sky.enumeration;
/**
* 数据库操作类型
*/
public enum OperationType {
/**
* 更新操作
*/
UPDATE,
/**
* 插入操作
*/
INSERT
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/enumeration/OperationType.java
|
Java
|
unknown
| 191
|
package com.sky.exception;
/**
* 账号被锁定异常
*/
public class AccountLockedException extends BaseException {
public AccountLockedException() {
}
public AccountLockedException(String msg) {
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/AccountLockedException.java
|
Java
|
unknown
| 244
|
package com.sky.exception;
/**
* 账号不存在异常
*/
public class AccountNotFoundException extends BaseException {
public AccountNotFoundException() {
}
public AccountNotFoundException(String msg) {
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/AccountNotFoundException.java
|
Java
|
unknown
| 250
|
package com.sky.exception;
public class AddressBookBusinessException extends BaseException {
public AddressBookBusinessException(String msg) {
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/AddressBookBusinessException.java
|
Java
|
unknown
| 178
|
package com.sky.exception;
/**
* 业务异常
*/
public class BaseException extends RuntimeException {
public BaseException() {
}
public BaseException(String msg) {
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/BaseException.java
|
Java
|
unknown
| 211
|
package com.sky.exception;
public class DeletionNotAllowedException extends BaseException {
public DeletionNotAllowedException(String msg) {
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/DeletionNotAllowedException.java
|
Java
|
unknown
| 176
|
package com.sky.exception;
/**
* 登录失败
*/
public class LoginFailedException extends BaseException{
public LoginFailedException(String msg){
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/LoginFailedException.java
|
Java
|
unknown
| 182
|
package com.sky.exception;
public class OrderBusinessException extends BaseException {
public OrderBusinessException(String msg) {
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/OrderBusinessException.java
|
Java
|
unknown
| 166
|
package com.sky.exception;
/**
* 密码修改失败异常
*/
public class PasswordEditFailedException extends BaseException{
public PasswordEditFailedException(String msg){
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/PasswordEditFailedException.java
|
Java
|
unknown
| 210
|
package com.sky.exception;
/**
* 密码错误异常
*/
public class PasswordErrorException extends BaseException {
public PasswordErrorException() {
}
public PasswordErrorException(String msg) {
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/PasswordErrorException.java
|
Java
|
unknown
| 241
|
package com.sky.exception;
/**
* 套餐启用失败异常
*/
public class SetmealEnableFailedException extends BaseException {
public SetmealEnableFailedException(){}
public SetmealEnableFailedException(String msg){
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/SetmealEnableFailedException.java
|
Java
|
unknown
| 257
|
package com.sky.exception;
public class ShoppingCartBusinessException extends BaseException {
public ShoppingCartBusinessException(String msg) {
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/ShoppingCartBusinessException.java
|
Java
|
unknown
| 180
|
package com.sky.exception;
public class UserNotLoginException extends BaseException {
public UserNotLoginException() {
}
public UserNotLoginException(String msg) {
super(msg);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/exception/UserNotLoginException.java
|
Java
|
unknown
| 208
|
package com.sky.json;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
/**
* 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象
* 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象]
* 从Java对象生成JSON的过程称为 [序列化Java对象到JSON]
*/
public class JacksonObjectMapper extends ObjectMapper {
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
//public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
public JacksonObjectMapper() {
super();
//收到未知属性时不报异常
this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
//反序列化时,属性不存在的兼容处理
this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
SimpleModule simpleModule = new SimpleModule()
.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
//注册功能模块 例如,可以添加自定义序列化器和反序列化器
this.registerModule(simpleModule);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/json/JacksonObjectMapper.java
|
Java
|
unknown
| 2,759
|
package com.sky.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/properties/AliOssProperties.java
|
Java
|
unknown
| 404
|
package com.sky.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "sky.jwt")
@Data
public class JwtProperties {
/**
* 管理端员工生成jwt令牌相关配置
*/
private String adminSecretKey;
private long adminTtl;
private String adminTokenName;
/**
* 用户端微信用户生成jwt令牌相关配置
*/
private String userSecretKey;
private long userTtl;
private String userTokenName;
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/properties/JwtProperties.java
|
Java
|
unknown
| 600
|
package com.sky.properties;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "sky.wechat")
@Data
public class WeChatProperties {
private String appid; //小程序的appid
private String secret; //小程序的秘钥
private String mchid; //商户号
private String mchSerialNo; //商户API证书的证书序列号
private String privateKeyFilePath; //商户私钥文件
private String apiV3Key; //证书解密的密钥
private String weChatPayCertFilePath; //平台证书
private String notifyUrl; //支付成功的回调地址
private String refundNotifyUrl; //退款成功的回调地址
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/properties/WeChatProperties.java
|
Java
|
unknown
| 831
|
package com.sky.result;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
/**
* 封装分页查询结果
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageResult implements Serializable {
private long total; //总记录数
private List records; //当前页数据集合
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/result/PageResult.java
|
Java
|
unknown
| 391
|
package com.sky.result;
import lombok.Data;
import java.io.Serializable;
/**
* 后端统一返回结果
* @param <T>
*/
@Data
public class Result<T> implements Serializable {
private Integer code; //编码:1成功,0和其它数字为失败
private String msg; //错误信息
private T data; //数据
public static <T> Result<T> success() {
Result<T> result = new Result<T>();
result.code = 1;
return result;
}
public static <T> Result<T> success(T object) {
Result<T> result = new Result<T>();
result.data = object;
result.code = 1;
return result;
}
public static <T> Result<T> error(String msg) {
Result result = new Result();
result.msg = msg;
result.code = 0;
return result;
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/result/Result.java
|
Java
|
unknown
| 821
|
package com.sky.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
/**
* 文件上传
*
* @param bytes
* @param objectName
* @return
*/
public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//文件访问路径规则 https://BucketName.Endpoint/ObjectName
StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
log.info("文件上传到:{}", stringBuilder.toString());
return stringBuilder.toString();
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/utils/AliOssUtil.java
|
Java
|
unknown
| 2,338
|
package com.sky.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Http工具类
*/
public class HttpClientUtil {
static final int TIMEOUT_MSEC = 5 * 1000;
/**
* 发送GET方式请求
* @param url
* @param paramMap
* @return
*/
public static String doGet(String url,Map<String,String> paramMap){
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
CloseableHttpResponse response = null;
try{
URIBuilder builder = new URIBuilder(url);
if(paramMap != null){
for (String key : paramMap.keySet()) {
builder.addParameter(key,paramMap.get(key));
}
}
URI uri = builder.build();
//创建GET请求
HttpGet httpGet = new HttpGet(uri);
//发送请求
response = httpClient.execute(httpGet);
//判断响应状态
if(response.getStatusLine().getStatusCode() == 200){
result = EntityUtils.toString(response.getEntity(),"UTF-8");
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 发送POST方式请求
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost(String url, Map<String, String> paramMap) throws IOException {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (paramMap != null) {
List<NameValuePair> paramList = new ArrayList();
for (Map.Entry<String, String> param : paramMap.entrySet()) {
paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
httpPost.setConfig(builderRequestConfig());
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 发送POST方式请求
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
if (paramMap != null) {
//构造json格式数据
JSONObject jsonObject = new JSONObject();
for (Map.Entry<String, String> param : paramMap.entrySet()) {
jsonObject.put(param.getKey(),param.getValue());
}
StringEntity entity = new StringEntity(jsonObject.toString(),"utf-8");
//设置请求编码
entity.setContentEncoding("utf-8");
//设置数据类型
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
httpPost.setConfig(builderRequestConfig());
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
private static RequestConfig builderRequestConfig() {
return RequestConfig.custom()
.setConnectTimeout(TIMEOUT_MSEC)
.setConnectionRequestTimeout(TIMEOUT_MSEC)
.setSocketTimeout(TIMEOUT_MSEC).build();
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/utils/HttpClientUtil.java
|
Java
|
unknown
| 5,577
|
package com.sky.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
public class JwtUtil {
/**
* 生成jwt
* 使用Hs256算法, 私匙使用固定秘钥
*
* @param secretKey jwt秘钥
* @param ttlMillis jwt过期时间(毫秒)
* @param claims 设置的信息
* @return
*/
public static String createJWT(String secretKey, long ttlMillis, Map<String, Object> claims) {
// 指定签名的时候使用的签名算法,也就是header那部分
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
// 生成JWT的时间
long expMillis = System.currentTimeMillis() + ttlMillis;
Date exp = new Date(expMillis);
// 设置jwt的body
JwtBuilder builder = Jwts.builder()
// 如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的
.setClaims(claims)
// 设置签名使用的签名算法和签名使用的秘钥
.signWith(signatureAlgorithm, secretKey.getBytes(StandardCharsets.UTF_8))
// 设置过期时间
.setExpiration(exp);
return builder.compact();
}
/**
* Token解密
*
* @param secretKey jwt秘钥 此秘钥一定要保留好在服务端, 不能暴露出去, 否则sign就可以被伪造, 如果对接多个客户端建议改造成多个
* @param token 加密后的token
* @return
*/
public static Claims parseJWT(String secretKey, String token) {
// 得到DefaultJwtParser
Claims claims = Jwts.parser()
// 设置签名的秘钥
.setSigningKey(secretKey.getBytes(StandardCharsets.UTF_8))
// 设置需要解析的jwt
.parseClaimsJws(token).getBody();
return claims;
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/utils/JwtUtil.java
|
Java
|
unknown
| 2,156
|
package com.sky.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.properties.WeChatProperties;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
/**
* 微信支付工具类
*/
@Component
public class WeChatPayUtil {
//微信支付下单接口地址
public static final String JSAPI = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
//申请退款接口地址
public static final String REFUNDS = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds";
@Autowired
private WeChatProperties weChatProperties;
/**
* 获取调用微信接口的客户端工具对象
*
* @return
*/
private CloseableHttpClient getClient() {
PrivateKey merchantPrivateKey = null;
try {
//merchantPrivateKey商户API私钥,如何加载商户API私钥请看常见问题
merchantPrivateKey = PemUtil.loadPrivateKey(new FileInputStream(new File(weChatProperties.getPrivateKeyFilePath())));
//加载平台证书文件
X509Certificate x509Certificate = PemUtil.loadCertificate(new FileInputStream(new File(weChatProperties.getWeChatPayCertFilePath())));
//wechatPayCertificates微信支付平台证书列表。你也可以使用后面章节提到的“定时更新平台证书功能”,而不需要关心平台证书的来龙去脉
List<X509Certificate> wechatPayCertificates = Arrays.asList(x509Certificate);
WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
.withMerchant(weChatProperties.getMchid(), weChatProperties.getMchSerialNo(), merchantPrivateKey)
.withWechatPay(wechatPayCertificates);
// 通过WechatPayHttpClientBuilder构造的HttpClient,会自动的处理签名和验签
CloseableHttpClient httpClient = builder.build();
return httpClient;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 发送post方式请求
*
* @param url
* @param body
* @return
*/
private String post(String url, String body) throws Exception {
CloseableHttpClient httpClient = getClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString());
httpPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
httpPost.addHeader("Wechatpay-Serial", weChatProperties.getMchSerialNo());
httpPost.setEntity(new StringEntity(body, "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
String bodyAsString = EntityUtils.toString(response.getEntity());
return bodyAsString;
} finally {
httpClient.close();
response.close();
}
}
/**
* 发送get方式请求
*
* @param url
* @return
*/
private String get(String url) throws Exception {
CloseableHttpClient httpClient = getClient();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString());
httpGet.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
httpGet.addHeader("Wechatpay-Serial", weChatProperties.getMchSerialNo());
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
String bodyAsString = EntityUtils.toString(response.getEntity());
return bodyAsString;
} finally {
httpClient.close();
response.close();
}
}
/**
* jsapi下单
*
* @param orderNum 商户订单号
* @param total 总金额
* @param description 商品描述
* @param openid 微信用户的openid
* @return
*/
private String jsapi(String orderNum, BigDecimal total, String description, String openid) throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("appid", weChatProperties.getAppid());
jsonObject.put("mchid", weChatProperties.getMchid());
jsonObject.put("description", description);
jsonObject.put("out_trade_no", orderNum);
jsonObject.put("notify_url", weChatProperties.getNotifyUrl());
JSONObject amount = new JSONObject();
amount.put("total", total.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).intValue());
amount.put("currency", "CNY");
jsonObject.put("amount", amount);
JSONObject payer = new JSONObject();
payer.put("openid", openid);
jsonObject.put("payer", payer);
String body = jsonObject.toJSONString();
return post(JSAPI, body);
}
/**
* 小程序支付
*
* @param orderNum 商户订单号
* @param total 金额,单位 元
* @param description 商品描述
* @param openid 微信用户的openid
* @return
*/
public JSONObject pay(String orderNum, BigDecimal total, String description, String openid) throws Exception {
//统一下单,生成预支付交易单
String bodyAsString = jsapi(orderNum, total, description, openid);
//解析返回结果
JSONObject jsonObject = JSON.parseObject(bodyAsString);
System.out.println(jsonObject);
String prepayId = jsonObject.getString("prepay_id");
if (prepayId != null) {
String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
String nonceStr = RandomStringUtils.randomNumeric(32);
ArrayList<Object> list = new ArrayList<>();
list.add(weChatProperties.getAppid());
list.add(timeStamp);
list.add(nonceStr);
list.add("prepay_id=" + prepayId);
//二次签名,调起支付需要重新签名
StringBuilder stringBuilder = new StringBuilder();
for (Object o : list) {
stringBuilder.append(o).append("\n");
}
String signMessage = stringBuilder.toString();
byte[] message = signMessage.getBytes();
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(PemUtil.loadPrivateKey(new FileInputStream(new File(weChatProperties.getPrivateKeyFilePath()))));
signature.update(message);
String packageSign = Base64.getEncoder().encodeToString(signature.sign());
//构造数据给微信小程序,用于调起微信支付
JSONObject jo = new JSONObject();
jo.put("timeStamp", timeStamp);
jo.put("nonceStr", nonceStr);
jo.put("package", "prepay_id=" + prepayId);
jo.put("signType", "RSA");
jo.put("paySign", packageSign);
return jo;
}
return jsonObject;
}
/**
* 申请退款
*
* @param outTradeNo 商户订单号
* @param outRefundNo 商户退款单号
* @param refund 退款金额
* @param total 原订单金额
* @return
*/
public String refund(String outTradeNo, String outRefundNo, BigDecimal refund, BigDecimal total) throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("out_trade_no", outTradeNo);
jsonObject.put("out_refund_no", outRefundNo);
JSONObject amount = new JSONObject();
amount.put("refund", refund.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).intValue());
amount.put("total", total.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).intValue());
amount.put("currency", "CNY");
jsonObject.put("amount", amount);
jsonObject.put("notify_url", weChatProperties.getRefundNotifyUrl());
String body = jsonObject.toJSONString();
//调用申请退款接口
return post(REFUNDS, body);
}
}
|
2301_80211016/cqwm
|
sky-common/src/main/java/com/sky/utils/WeChatPayUtil.java
|
Java
|
unknown
| 9,096
|
package com.sky.dto;
import lombok.Data;
import java.io.Serializable;
@Data
public class CategoryDTO implements Serializable {
//主键
private Long id;
//类型 1 菜品分类 2 套餐分类
private Integer type;
//分类名称
private String name;
//排序
private Integer sort;
}
|
2301_80211016/cqwm
|
sky-pojo/src/main/java/com/sky/dto/CategoryDTO.java
|
Java
|
unknown
| 323
|
package com.sky.dto;
import lombok.Data;
import java.io.Serializable;
@Data
public class CategoryPageQueryDTO implements Serializable {
//页码
private int page;
//每页记录数
private int pageSize;
//分类名称
private String name;
//分类类型 1菜品分类 2套餐分类
private Integer type;
}
|
2301_80211016/cqwm
|
sky-pojo/src/main/java/com/sky/dto/CategoryPageQueryDTO.java
|
Java
|
unknown
| 347
|
package com.sky.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DataOverViewQueryDTO implements Serializable {
private LocalDateTime begin;
private LocalDateTime end;
}
|
2301_80211016/cqwm
|
sky-pojo/src/main/java/com/sky/dto/DataOverViewQueryDTO.java
|
Java
|
unknown
| 378
|
package com.sky.dto;
import com.sky.entity.DishFlavor;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@Data
public class DishDTO implements Serializable {
private Long id;
//菜品名称
private String name;
//菜品分类id
private Long categoryId;
//菜品价格
private BigDecimal price;
//图片
private String image;
//描述信息
private String description;
//0 停售 1 起售
private Integer status;
//口味
private List<DishFlavor> flavors = new ArrayList<>();
}
|
2301_80211016/cqwm
|
sky-pojo/src/main/java/com/sky/dto/DishDTO.java
|
Java
|
unknown
| 620
|