版本比较
塔防
标题
增加 1 行删除 1 行
1教师模拟器1塔防
正文
增加 1236 行删除 2576 行
2 行未改动345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962 行未改动<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>教师模拟器 - 体验教师的日常工作</title><!-- Tailwind CSS v3 --><script src="https://cdn.tailwindcss.com"></script><!-- Font Awesome --><link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet"><script>tailwind.config = {theme: {extend: {colors: {primary: '#3b82f6', // 蓝色secondary: '#10b981', // 绿色accent: '#f59e0b', // 橙色danger: '#ef4444', // 红色dark: '#1e293b',light: '#f8fafc'},fontFamily: {sans: ['Inter', 'system-ui', 'sans-serif'],},animation: {'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite','bounce-slow': 'bounce 2s infinite','fade-in': 'fadeIn 0.5s ease-in-out','slide-in': 'slideIn 0.5s ease-in-out',},keyframes: {fadeIn: {'0%': { opacity: '0' },'100%': { opacity: '1' },},slideIn: {'0%': { transform: 'translateY(20px)', opacity: '0' },'100%': { transform: 'translateY(0)', opacity: '1' },}}}}}</script><style type="text/tailwindcss">@layer utilities {.text-shadow {text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);}.card-shadow {box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);}.transition-all-300 {transition: all 300ms ease-in-out;}.bg-pattern {background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%239C92AC' fill-opacity='0.05'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");}}</style><style>/* 自定义样式 */.pressure-bar {height: 8px;border-radius: 4px;transition: width 0.5s ease-in-out;}.student-card:hover {transform: translateY(-5px);}.activity-card {transition: all 0.3s ease;}.activity-card:hover {transform: scale(1.03);}.activity-card.selected {border: 2px solid #3b82f6;box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);}.week-card {min-height: 120px;}.notification {position: fixed;top: 20px;right: 20px;z-index: 1000;transform: translateX(400px);transition: transform 0.3s ease-in-out;}.notification.show {transform: translateX(0);}/* 加载动画 */.loading {display: inline-block;position: relative;width: 80px;height: 80px;}.loading div {position: absolute;top: 33px;width: 13px;height: 13px;border-radius: 50%;background: #3b82f6;animation-timing-function: cubic-bezier(0, 1, 1, 0);}.loading div:nth-child(1) {left: 8px;animation: loading1 0.6s infinite;}.loading div:nth-child(2) {left: 8px;animation: loading2 0.6s infinite;}.loading div:nth-child(3) {left: 32px;animation: loading2 0.6s infinite;}.loading div:nth-child(4) {left: 56px;animation: loading3 0.6s infinite;}@keyframes loading1 {0% { transform: scale(0); }100% { transform: scale(1); }}@keyframes loading3 {0% { transform: scale(1); }100% { transform: scale(0); }}@keyframes loading2 {0% { transform: translate(0, 0); }100% { transform: translate(24px, 0); }}/* 成就解锁动画 */@keyframes achievementUnlock {0% { transform: scale(0) rotate(0deg); opacity: 0; }50% { transform: scale(1.2) rotate(180deg); opacity: 1; }100% { transform: scale(1) rotate(360deg); opacity: 1; }}.achievement-unlock {animation: achievementUnlock 1s ease-out forwards;}</style></head><body class="bg-gray-50 bg-pattern min-h-screen"><!-- 初始设置弹窗 --><div id="setupModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"><div class="bg-white rounded-lg shadow-xl p-8 max-w-md w-full animate-fade-in"><h2 class="text-2xl font-bold text-center mb-6 text-primary">欢迎来到教师模拟器!</h2><p class="text-gray-600 mb-6">请选择你将要工作的地区,不同地区有不同的教育环境和资源条件。</p><div class="space-y-4 mb-6"><div class="region-card p-4 border rounded-lg cursor-pointer hover:bg-blue-50 transition-all-300" data-region="city"><div class="flex items-center"><div class="w-12 h-12 bg-primary rounded-full flex items-center justify-center text-white mr-4"><i class="fa fa-building text-xl"></i></div><div><h3 class="font-bold text-lg">城市学校</h3><p class="text-sm text-gray-600">资源丰富,家长期望高,学生竞争压力大</p><div class="flex mt-2 text-sm"><span class="mr-4"><i class="fa fa-money text-green-500"></i> 班费: 1000元</span><span><i class="fa fa-users text-blue-500"></i> 学生: 40人</span></div></div></div></div><div class="region-card p-4 border rounded-lg cursor-pointer hover:bg-blue-50 transition-all-300" data-region="suburb"><div class="flex items-center"><div class="w-12 h-12 bg-secondary rounded-full flex items-center justify-center text-white mr-4"><i class="fa fa-tree text-xl"></i></div><div><h3 class="font-bold text-lg">郊区学校</h3><p class="text-sm text-gray-600">资源适中,家长配合度高,学生压力中等</p><div class="flex mt-2 text-sm"><span class="mr-4"><i class="fa fa-money text-green-500"></i> 班费: 700元</span><span><i class="fa fa-users text-blue-500"></i> 学生: 35人</span></div></div></div></div><div class="region-card p-4 border rounded-lg cursor-pointer hover:bg-blue-50 transition-all-300" data-region="rural"><div class="flex items-center"><div class="w-12 h-12 bg-accent rounded-full flex items-center justify-center text-white mr-4"><i class="fa fa-pagelines text-xl"></i></div><div><h3 class="font-bold text-lg">乡村学校</h3><p class="text-sm text-gray-600">资源有限,学生基础参差不齐,需要更多耐心</p><div class="flex mt-2 text-sm"><span class="mr-4"><i class="fa fa-money text-green-500"></i> 班费: 400元</span><span><i class="fa fa-users text-blue-500"></i> 学生: 30人</span></div></div></div></div></div><div class="text-center"><button id="startGame" class="bg-primary hover:bg-blue-600 text-white font-bold py-2 px-6 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed" disabled>开始游戏</button></div></div></div><!-- 主游戏界面 --><div id="gameContainer" class="flex flex-col h-screen hidden"><!-- 顶部状态栏 --><header class="bg-white shadow-md"><div class="container mx-auto px-4 py-3 flex justify-between items-center"><div class="flex items-center"><h1 class="text-2xl font-bold text-primary mr-6">教师模拟器</h1><div class="flex items-center bg-blue-50 px-3 py-1 rounded-full"><i class="fa fa-calendar text-primary mr-2"></i><span class="font-medium">第 <span id="currentWeek">1</span> 周</span></div></div><div class="flex items-center space-x-6"><div class="flex items-center"><i class="fa fa-money text-green-500 text-xl mr-2"></i><span class="font-bold text-lg">班费: <span id="classFund">0</span>元</span></div><div class="flex items-center"><i class="fa fa-users text-blue-500 text-xl mr-2"></i><span class="font-bold text-lg">班级状态: </span><span id="classStatus" class="ml-1 px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">良好</span></div><button id="achievementBtn" class="flex items-center bg-yellow-50 hover:bg-yellow-100 text-yellow-700 px-3 py-1 rounded-full transition-all"><i class="fa fa-trophy mr-2"></i><span>成就</span></button></div></div></header><!-- 主要内容区域 --><div class="flex flex-1 overflow-hidden"><!-- 左侧导航菜单 --><nav class="w-64 bg-white shadow-md overflow-y-auto"><div class="p-4"><h2 class="text-lg font-bold mb-4 text-gray-700 border-b pb-2">功能菜单</h2><ul class="space-y-2"><li><button class="nav-btn w-full flex items-center px-3 py-2 text-gray-700 rounded-lg hover:bg-blue-50 transition-all active" data-target="dashboard"><i class="fa fa-home w-6 text-primary"></i><span>班级概览</span></button></li><li><button class="nav-btn w-full flex items-center px-3 py-2 text-gray-700 rounded-lg hover:bg-blue-50 transition-all" data-target="students"><i class="fa fa-user-circle w-6 text-primary"></i><span>学生管理</span></button></li><li><button class="nav-btn w-full flex items-center px-3 py-2 text-gray-700 rounded-lg hover:bg-blue-50 transition-all" data-target="schedule"><i class="fa fa-calendar-check-o w-6 text-primary"></i><span>课程安排</span></button></li><li><button class="nav-btn w-full flex items-center px-3 py-2 text-gray-700 rounded-lg hover:bg-blue-50 transition-all" data-target="finances"><i class="fa fa-money w-6 text-primary"></i><span>班费管理</span></button></li><li><button class="nav-btn w-full flex items-center px-3 py-2 text-gray-700 rounded-lg hover:bg-blue-50 transition-all" data-target="events"><i class="fa fa-bell w-6 text-primary"></i><span>事件记录</span></button></li></ul></div><div class="p-4 border-t"><h2 class="text-lg font-bold mb-4 text-gray-700">游戏控制</h2><div class="space-y-3"><button id="nextWeekBtn" class="w-full bg-primary hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-lg transition-all flex items-center justify-center"><i class="fa fa-arrow-right mr-2"></i>进入下一周</button><button id="saveGameBtn" class="w-full bg-secondary hover:bg-green-600 text-white font-bold py-2 px-4 rounded-lg transition-all flex items-center justify-center"><i class="fa fa-save mr-2"></i>保存游戏</button><button id="restartGameBtn" class="w-full bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition-all flex items-center justify-center"><i class="fa fa-refresh mr-2"></i>重新开始</button></div></div></nav><!-- 右侧内容区域 --><main class="flex-1 overflow-y-auto p-6"><!-- 班级概览页面 --><section id="dashboard" class="page-content"><div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6"><!-- 班级基本信息 --><div class="bg-white rounded-lg shadow-md p-6"><h3 class="text-lg font-bold mb-4 text-gray-700 flex items-center"><i class="fa fa-info-circle text-primary mr-2"></i>班级信息</h3><div class="space-y-3"><div class="flex justify-between"><span class="text-gray-600">地区:</span><span id="regionDisplay" class="font-medium">--</span></div><div class="flex justify-between"><span class="text-gray-600">学生人数:</span><span id="studentCount" class="font-medium">--</span></div><div class="flex justify-between"><span class="text-gray-600">平均压力值:</span><div class="flex items-center"><div class="w-24 bg-gray-200 rounded-full h-2 mr-2"><div id="avgPressureBar" class="bg-yellow-500 h-2 rounded-full" style="width: 0%"></div></div><span id="avgPressureValue" class="font-medium">0%</span></div></div><div class="flex justify-between"><span class="text-gray-600">班级满意度:</span><div class="flex items-center"><div class="w-24 bg-gray-200 rounded-full h-2 mr-2"><div id="satisfactionBar" class="bg-green-500 h-2 rounded-full" style="width: 0%"></div></div><span id="satisfactionValue" class="font-medium">0%</span></div></div></div></div><!-- 本周活动 --><div class="bg-white rounded-lg shadow-md p-6"><h3 class="text-lg font-bold mb-4 text-gray-700 flex items-center"><i class="fa fa-calendar text-primary mr-2"></i>本周活动</h3><div id="weeklyActivity" class="text-center py-4 text-gray-500">尚未安排活动</div></div><!-- 最近事件 --><div class="bg-white rounded-lg shadow-md p-6"><h3 class="text-lg font-bold mb-4 text-gray-700 flex items-center"><i class="fa fa-bell text-primary mr-2"></i>最近事件</h3><div id="recentEvents" class="space-y-3 max-h-40 overflow-y-auto"><div class="text-center py-4 text-gray-500">暂无事件记录</div></div></div></div><!-- 学生压力分布 --><div class="bg-white rounded-lg shadow-md p-6 mb-6"><h3 class="text-lg font-bold mb-4 text-gray-700 flex items-center"><i class="fa fa-line-chart text-primary mr-2"></i>学生压力分布</h3><div class="h-64"><canvas id="pressureChart"></canvas></div></div><!-- 本周建议 --><div class="bg-white rounded-lg shadow-md p-6"><h3 class="text-lg font-bold mb-4 text-gray-700 flex items-center"><i class="fa fa-lightbulb-o text-primary mr-2"></i>本周建议</h3><div id="weeklySuggestion" class="p-4 bg-blue-50 rounded-lg text-gray-700">根据学生当前状态,建议本周安排一次轻松的班级活动,缓解学生压力。</div></div></section><!-- 学生管理页面 --><section id="students" class="page-content hidden"><div class="mb-6 flex justify-between items-center"><h2 class="text-2xl font-bold text-gray-800">学生管理</h2><div class="flex space-x-2"><div class="relative"><input type="text" id="studentSearch" placeholder="搜索学生..." class="pl-8 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"><i class="fa fa-search absolute left-3 top-3 text-gray-400"></i></div><select id="studentFilter" class="border rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary"><option value="all">全部学生</option><option value="high-pressure">高压力</option><option value="medium-pressure">中等压力</option><option value="low-pressure">低压力</option></select></div></div><div id="studentsContainer" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4"><!-- 学生卡片将通过JavaScript动态生成 --></div></section><!-- 课程安排页面 --><section id="schedule" class="page-content hidden"><div class="mb-6"><h2 class="text-2xl font-bold text-gray-800 mb-4">课程安排</h2><p class="text-gray-600">安排未来几周的教学活动。每个活动持续一周,会影响学生的压力和班级状态。</p></div><div class="grid grid-cols-1 lg:grid-cols-3 gap-6"><!-- 左侧活动选择 --><div class="bg-white rounded-lg shadow-md p-6"><h3 class="text-lg font-bold mb-4 text-gray-700">可用活动</h3><div class="space-y-3" id="activitiesList"><!-- 活动卡片将通过JavaScript动态生成 --></div></div><!-- 右侧课程表 --><div class="lg:col-span-2"><h3 class="text-lg font-bold mb-4 text-gray-700">课程表</h3><div class="grid grid-cols-1 md:grid-cols-2 gap-4" id="scheduleContainer"><!-- 周次卡片将通过JavaScript动态生成 --></div></div></div></section><!-- 班费管理页面 --><section id="finances" class="page-content hidden"><div class="mb-6"><h2 class="text-2xl font-bold text-gray-800 mb-4">班费管理</h2><p class="text-gray-600">管理班级财务,记录收入和支出。</p></div><div class="grid grid-cols-1 lg:grid-cols-3 gap-6"><!-- 左侧财务概览 --><div class="bg-white rounded-lg shadow-md p-6"><h3 class="text-lg font-bold mb-4 text-gray-700">财务概览</h3><div class="space-y-4"><div class="flex justify-between items-center"><span class="text-gray-600">当前余额:</span><span id="currentBalance" class="text-xl font-bold text-green-600">0元</span></div><div class="flex justify-between"><span class="text-gray-600">总收入:</span><span id="totalIncome" class="font-medium text-green-600">0元</span></div><div class="flex justify-between"><span class="text-gray-600">总支出:</span><span id="totalExpense" class="font-medium text-red-600">0元</span></div><div class="border-t my-2"></div><div><h4 class="font-medium mb-2">快速操作</h4><div class="space-y-2"><button id="collectFeeBtn" class="w-full bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-lg transition-all flex items-center justify-center"><i class="fa fa-plus-circle mr-2"></i>收取班费</button><button id="addExpenseBtn" class="w-full bg-red-500 hover:bg-red-600 text-white py-2 px-4 rounded-lg transition-all flex items-center justify-center"><i class="fa fa-minus-circle mr-2"></i>添加支出</button></div></div></div></div><!-- 右侧财务记录 --><div class="lg:col-span-2 bg-white rounded-lg shadow-md p-6"><h3 class="text-lg font-bold mb-4 text-gray-700">财务记录</h3><div class="overflow-x-auto"><table class="min-w-full divide-y divide-gray-200"><thead><tr><th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">日期</th><th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th><th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">描述</th><th class="px-6 py-3 bg-gray-50 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">金额</th></tr></thead><tbody id="financeRecords" class="bg-white divide-y divide-gray-200"><!-- 财务记录将通过JavaScript动态生成 --></tbody></table></div></div></div></section><!-- 事件记录页面 --><section id="events" class="page-content hidden"><div class="mb-6"><h2 class="text-2xl font-bold text-gray-800 mb-4">事件记录</h2><p class="text-gray-600">查看班级发生的重要事件记录。</p></div><div class="bg-white rounded-lg shadow-md p-6"><div class="space-y-4" id="eventsContainer"><!-- 事件记录将通过JavaScript动态生成 --></div></div></section></main></div></div><!-- 成就弹窗 --><div id="achievementModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"><div class="bg-white rounded-lg shadow-xl p-6 max-w-2xl w-full max-h-[80vh] overflow-y-auto animate-fade-in"><div class="flex justify-between items-center mb-6"><h2 class="text-2xl font-bold text-yellow-600 flex items-center"><i class="fa fa-trophy mr-2"></i>成就系统</h2><button id="closeAchievementBtn" class="text-gray-500 hover:text-gray-700"><i class="fa fa-times text-xl"></i></button></div><div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4" id="achievementsContainer"><!-- 成就将通过JavaScript动态生成 --></div></div></div><!-- 收取班费弹窗 --><div id="collectFeeModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"><div class="bg-white rounded-lg shadow-xl p-6 max-w-md w-full animate-fade-in"><h2 class="text-xl font-bold mb-4 text-gray-800">收取班费</h2><div class="space-y-4"><div><label class="block text-gray-700 mb-2">金额 (元)</label><input type="number" id="feeAmount" class="w-full border rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary" min="1" max="100" value="20"></div><div><label class="block text-gray-700 mb-2">说明</label><input type="text" id="feeDescription" class="w-full border rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary" placeholder="例如:购买班级用品"></div><div class="flex justify-end space-x-3 pt-4"><button id="cancelCollectFeeBtn" class="px-4 py-2 border rounded-lg hover:bg-gray-100 transition-all">取消</button><button id="confirmCollectFeeBtn" class="px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg transition-all">确认</button></div></div></div></div><!-- 添加支出弹窗 --><div id="addExpenseModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"><div class="bg-white rounded-lg shadow-xl p-6 max-w-md w-full animate-fade-in"><h2 class="text-xl font-bold mb-4 text-gray-800">添加支出</h2><div class="space-y-4"><div><label class="block text-gray-700 mb-2">金额 (元)</label><input type="number" id="expenseAmount" class="w-full border rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary" min="1" value="50"></div><div><label class="block text-gray-700 mb-2">用途</label><input type="text" id="expenseDescription" class="w-full border rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary" placeholder="例如:购买教学材料"></div><div class="flex justify-end space-x-3 pt-4"><button id="cancelAddExpenseBtn" class="px-4 py-2 border rounded-lg hover:bg-gray-100 transition-all">取消</button><button id="confirmAddExpenseBtn" class="px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-all">确认</button></div></div></div></div><!-- 随机事件弹窗 --><div id="eventModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"><div class="bg-white rounded-lg shadow-xl p-6 max-w-md w-full animate-fade-in"><div class="flex items-center mb-4"><div id="eventIcon" class="w-12 h-12 bg-yellow-500 rounded-full flex items-center justify-center text-white mr-4"><i class="fa fa-exclamation-triangle text-xl"></i></div><h2 id="eventTitle" class="text-xl font-bold text-gray-800">事件标题</h2></div><p id="eventDescription" class="text-gray-600 mb-6">事件描述内容...</p><div id="eventOptions" class="space-y-3"><!-- 事件选项将通过JavaScript动态生成 --></div></div></div><!-- 通知组件 --><div id="notification" class="notification"><div class="bg-white rounded-lg shadow-lg p-4 max-w-sm"><div class="flex items-start"><div id="notificationIcon" class="w-8 h-8 rounded-full flex items-center justify-center mr-3"><i id="notificationIconI" class="fa"></i></div><div class="flex-1"><h3 id="notificationTitle" class="font-bold text-gray-800"></h3><p id="notificationMessage" class="text-sm text-gray-600"></p></div><button id="closeNotification" class="text-gray-400 hover:text-gray-600"><i class="fa fa-times"></i></button></div></div></div><!-- Chart.js --><script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script><script>// 游戏状态let gameState = {region: null,currentWeek: 1,classFund: 0,students: [],schedule: [],financeRecords: [],events: [],achievements: [],classStatus: {pressure: 0,satisfaction: 50},isGameOver: false};// 地区配置const regions = {city: {name: "城市学校",initialFund: 1000,studentCount: 40,description: "资源丰富,家长期望高,学生竞争压力大",pressureModifier: 1.2,fundModifier: 1.5},suburb: {name: "郊区学校",initialFund: 700,studentCount: 35,description: "资源适中,家长配合度高,学生压力中等",pressureModifier: 1.0,fundModifier: 1.0},rural: {name: "乡村学校",initialFund: 400,studentCount: 30,description: "资源有限,学生基础参差不齐,需要更多耐心",pressureModifier: 0.8,fundModifier: 0.7}};// 活动配置const activities = {regularClass: {name: "常规上课",description: "进行正常的教学活动",cost: 0,pressureEffect: 10,satisfactionEffect: 0,fundEffect: 0,icon: "fa-book",color: "bg-blue-500",category: "teaching"},exam: {name: "考试周",description: "进行班级测验和考试",cost: 50,pressureEffect: 30,satisfactionEffect: -15,fundEffect: 0,icon: "fa-pencil-square-o",color: "bg-red-500",category: "assessment"},fieldTrip: {name: "研学旅行",description: "组织学生进行户外学习活动",cost: 200,pressureEffect: -20,satisfactionEffect: 25,fundEffect: -200,icon: "fa-bus",color: "bg-green-500",category: "activity"},holiday: {name: "放假休息",description: "给学生一周的休息时间",cost: 0,pressureEffect: -30,satisfactionEffect: 10,fundEffect: 0,icon: "fa-sun-o",color: "bg-yellow-500",category: "break"},competition: {name: "学科竞赛",description: "组织学生参加学科竞赛",cost: 100,pressureEffect: 20,satisfactionEffect: 15,fundEffect: 100,icon: "fa-trophy",color: "bg-purple-500",category: "competition"},clubActivity: {name: "社团活动",description: "开展丰富多彩的社团活动",cost: 80,pressureEffect: -15,satisfactionEffect: 20,fundEffect: 0,icon: "fa-users",color: "bg-pink-500",category: "activity"},parentMeeting: {name: "家长会",description: "与家长沟通学生学习情况",cost: 30,pressureEffect: 5,satisfactionEffect: 10,fundEffect: 50,icon: "fa-comments",color: "bg-indigo-500",category: "communication"},charity: {name: "公益活动",description: "组织学生参与社会公益",cost: 60,pressureEffect: -10,satisfactionEffect: 15,fundEffect: 0,icon: "fa-heart",color: "bg-red-400",category: "activity"}};// 随机事件配置const randomEvents = [{id: "studentConflict",title: "学生冲突",description: "两名学生在课堂上发生了激烈争执,需要你介入处理。",icon: "fa-exclamation-triangle",iconColor: "bg-red-500",options: [{text: "严厉批评双方",effects: {pressure: 15,satisfaction: -10,fund: 0},result: "你严厉批评了冲突的学生,课堂秩序得到恢复,但学生们的压力有所增加。"},{text: "耐心调解,了解原因",effects: {pressure: -5,satisfaction: 5,fund: 0},result: "你耐心地了解了冲突原因并成功调解,学生们对你的处理方式表示认可。"},{text: "让他们课后自行解决",effects: {pressure: 10,satisfaction: -5,fund: 0},result: "你决定让学生课后自行解决,但冲突没有得到很好的解决,班级氛围受到了一些影响。"}]},{id: "parentComplaint",title: "家长投诉",description: "一位家长对你的教学方法提出了投诉,认为作业量过大。",icon: "fa-user-times",iconColor: "bg-orange-500",options: [{text: "接受建议,减少作业量",effects: {pressure: -10,satisfaction: 5,fund: 0},result: "你接受了家长的建议,适当减少了作业量,学生们的压力有所缓解。"},{text: "解释教学理念,坚持原则",effects: {pressure: 5,satisfaction: -5,fund: 0},result: "你向家长解释了你的教学理念,但坚持了原有的作业量,部分家长对此仍有不满。"},{text: "组织家长会详细说明",effects: {pressure: 0,satisfaction: 10,fund: -50},result: "你组织了一次家长会,详细说明了教学计划和作业安排的目的,获得了大多数家长的理解和支持。"}]},{id: "teachingInspection",title: "教学检查",description: "学校将进行教学检查,需要准备公开课展示。",icon: "fa-search",iconColor: "bg-blue-500",options: [{text: "精心准备,展示最佳状态",effects: {pressure: 10,satisfaction: 15,fund: -100},result: "你花费大量时间和精力准备公开课,展示了精彩的教学内容,获得了领导的高度评价。"},{text: "正常教学,不特意准备",effects: {pressure: 5,satisfaction: -5,fund: 0},result: "你选择以平常的教学状态迎接检查,虽然没有特别突出,但也展示了真实的教学水平。"},{text: "与学生一起准备特别活动",effects: {pressure: -5,satisfaction: 20,fund: -50},result: "你与学生一起策划了一个特别的教学活动,既展示了教学成果,又增强了班级凝聚力。"}]},{id: "studentAchievement",title: "学生成就",description: "你的学生在市级比赛中获得了优异成绩!",icon: "fa-trophy",iconColor: "bg-yellow-500",options: [{text: "在班级中表扬并奖励学生",effects: {pressure: -5,satisfaction: 15,fund: -50},result: "你在班级中隆重表扬了获奖学生,并给予了适当奖励,激发了其他学生的学习热情。"},{text: "组织经验分享会",effects: {pressure: 0,satisfaction: 10,fund: -30},result: "你组织了一次经验分享会,让获奖学生分享学习心得,促进了班级整体进步。"},{text: "向家长和学校汇报这一喜讯",effects: {pressure: 0,satisfaction: 5,fund: 100},result: "你及时向家长和学校汇报了这一喜讯,学校给予了班级一定的奖励。"}]},{id: "equipmentFailure",title: "设备故障",description: "教室的多媒体设备出现了故障,影响正常教学。",icon: "fa-exclamation-circle",iconColor: "bg-gray-500",options: [{text: "临时调整教学计划,使用传统教学方式",effects: {pressure: 5,satisfaction: 0,fund: 0},result: "你灵活调整了教学计划,使用传统的教学方式完成了课程,学生们适应良好。"},{text: "联系维修人员紧急修复",effects: {pressure: -5,satisfaction: 5,fund: -100},result: "你立即联系了维修人员,设备很快得到了修复,教学活动得以顺利进行。"},{text: "组织学生进行户外教学",effects: {pressure: -10,satisfaction: 15,fund: -30},result: "你决定将课堂移至户外,进行了一次别开生面的教学活动,学生们非常喜欢这种方式。"}]}];// 成就配置const achievements = [{id: "firstWeek",title: "新的开始",description: "完成第一周的教学工作",icon: "fa-star",iconColor: "bg-yellow-500",condition: (state) => state.currentWeek >= 2,reward: {fund: 100},unlocked: false},{id: "pressureControl",title: "压力管理大师",description: "将班级平均压力保持在30%以下连续4周",icon: "fa-heartbeat",iconColor: "bg-green-500",condition: (state) => {// 检查最近4周的压力记录if (state.events.length < 4) return false;let recentEvents = state.events.slice(-4);let validWeeks = 0;for (let event of recentEvents) {if (event.type === "weekEnd" && event.data && event.data.avgPressure <= 30) {validWeeks++;}}return validWeeks >= 4;},reward: {fund: 200},unlocked: false},{id: "financeMaster",title: "理财高手",description: "班费余额达到2000元",icon: "fa-money",iconColor: "bg-green-600",condition: (state) => state.classFund >= 2000,reward: {fund: 300},unlocked: false},{id: "eventHandler",title: "事件处理专家",description: "成功处理10个随机事件",icon: "fa-exclamation-triangle",iconColor: "bg-orange-500",condition: (state) => {let eventCount = 0;for (let event of state.events) {if (event.type === "randomEvent") {eventCount++;}}return eventCount >= 10;},reward: {fund: 250},unlocked: false},{id: "studentSatisfaction",title: "学生喜爱的老师",description: "班级满意度达到80%以上",icon: "fa-smile-o",iconColor: "bg-blue-500",condition: (state) => state.classStatus.satisfaction >= 80,reward: {fund: 150},unlocked: false},{id: "seasonedTeacher",title: "资深教师",description: "完成20周的教学工作",icon: "fa-graduation-cap",iconColor: "bg-purple-500",condition: (state) => state.currentWeek >= 21,reward: {fund: 500},unlocked: false}];// DOM元素const setupModal = document.getElementById('setupModal');const gameContainer = document.getElementById('gameContainer');const regionCards = document.querySelectorAll('.region-card');const startGameBtn = document.getElementById('startGame');const navButtons = document.querySelectorAll('.nav-btn');const pageContents = document.querySelectorAll('.page-content');const nextWeekBtn = document.getElementById('nextWeekBtn');const saveGameBtn = document.getElementById('saveGameBtn');const restartGameBtn = document.getElementById('restartGameBtn');const achievementBtn = document.getElementById('achievementBtn');const achievementModal = document.getElementById('achievementModal');const closeAchievementBtn = document.getElementById('closeAchievementBtn');const collectFeeBtn = document.getElementById('collectFeeBtn');const collectFeeModal = document.getElementById('collectFeeModal');const cancelCollectFeeBtn = document.getElementById('cancelCollectFeeBtn');const confirmCollectFeeBtn = document.getElementById('confirmCollectFeeBtn');const addExpenseBtn = document.getElementById('addExpenseBtn');const addExpenseModal = document.getElementById('addExpenseModal');const cancelAddExpenseBtn = document.getElementById('cancelAddExpenseBtn');const confirmAddExpenseBtn = document.getElementById('confirmAddExpenseBtn');const eventModal = document.getElementById('eventModal');const notification = document.getElementById('notification');const closeNotification = document.getElementById('closeNotification');const studentSearch = document.getElementById('studentSearch');const studentFilter = document.getElementById('studentFilter');// 初始化游戏function initGame() {// 地区选择regionCards.forEach(card => {card.addEventListener('click', () => {// 移除其他卡片的选中状态regionCards.forEach(c => c.classList.remove('bg-blue-100', 'border-primary'));// 添加当前卡片的选中状态card.classList.add('bg-blue-100', 'border-primary');// 获取选中的地区const region = card.getAttribute('data-region');gameState.region = region;// 启用开始游戏按钮startGameBtn.disabled = false;});});// 开始游戏按钮startGameBtn.addEventListener('click', () => {if (!gameState.region) return;// 初始化游戏状态initializeGameState();// 隐藏设置弹窗,显示游戏界面setupModal.classList.add('hidden');gameContainer.classList.remove('hidden');// 更新UIupdateUI();// 生成学生generateStudents();// 初始化课程表initializeSchedule();// 初始化财务记录initializeFinanceRecords();// 显示欢迎通知showNotification('欢迎来到教师模拟器!', 'info', '你已成功创建班级,开始你的教师生涯吧!');});// 导航按钮navButtons.forEach(button => {button.addEventListener('click', () => {// 移除所有按钮的激活状态navButtons.forEach(btn => btn.classList.remove('active', 'bg-blue-50', 'text-primary'));// 添加当前按钮的激活状态button.classList.add('active', 'bg-blue-50', 'text-primary');// 获取目标页面const target = button.getAttribute('data-target');// 隐藏所有页面pageContents.forEach(page => page.classList.add('hidden'));// 显示目标页面document.getElementById(target).classList.remove('hidden');// 如果是学生页面,更新学生列表if (target === 'students') {renderStudents();}// 如果是课程安排页面,更新课程表if (target === 'schedule') {renderSchedule();renderActivities();}// 如果是财务页面,更新财务记录if (target === 'finances') {renderFinanceRecords();}// 如果是事件页面,更新事件记录if (target === 'events') {renderEvents();}});});// 进入下一周按钮nextWeekBtn.addEventListener('click', () => {// 检查是否已安排活动const currentWeekSchedule = gameState.schedule.find(s => s.week === gameState.currentWeek);if (!currentWeekSchedule) {showNotification('无法进入下一周', 'error', '请先为当前周安排活动');return;}// 处理当前周活动效果processWeekActivity(currentWeekSchedule.activity);// 增加周数gameState.currentWeek++;// 更新UIupdateUI();// 检查并触发随机事件checkRandomEvent();// 检查成就checkAchievements();// 检查游戏结束条件checkGameOver();});// 保存游戏按钮saveGameBtn.addEventListener('click', () => {// 保存游戏状态到localStoragelocalStorage.setItem('teacherSimulatorSave', JSON.stringify(gameState));showNotification('游戏已保存', 'success', '你的游戏进度已成功保存');});// 重新开始按钮restartGameBtn.addEventListener('click', () => {if (confirm('确定要重新开始游戏吗?当前进度将会丢失。')) {// 重置游戏状态gameState = {region: null,currentWeek: 1,classFund: 0,students: [],schedule: [],financeRecords: [],events: [],achievements: [],classStatus: {pressure: 0,satisfaction: 50},isGameOver: false};// 显示设置弹窗,隐藏游戏界面setupModal.classList.remove('hidden');gameContainer.classList.add('hidden');// 移除地区选择regionCards.forEach(c => c.classList.remove('bg-blue-100', 'border-primary'));// 禁用开始游戏按钮startGameBtn.disabled = true;}});// 成就按钮achievementBtn.addEventListener('click', () => {renderAchievements();achievementModal.classList.remove('hidden');});// 关闭成就弹窗closeAchievementBtn.addEventListener('click', () => {achievementModal.classList.add('hidden');});// 收取班费按钮collectFeeBtn.addEventListener('click', () => {collectFeeModal.classList.remove('hidden');});// 取消收取班费cancelCollectFeeBtn.addEventListener('click', () => {collectFeeModal.classList.add('hidden');});// 确认收取班费confirmCollectFeeBtn.addEventListener('click', () => {const amount = parseInt(document.getElementById('feeAmount').value);const description = document.getElementById('feeDescription').value || '收取班费';if (isNaN(amount) || amount <= 0) {showNotification('输入错误', 'error', '请输入有效的金额');return;}// 添加财务记录addFinanceRecord('income', description, amount);// 更新班费gameState.classFund += amount;// 添加事件addEvent('finance', `${description} (${amount}元)`, {type: 'income',amount: amount,description: description});// 更新UIupdateUI();// 关闭弹窗collectFeeModal.classList.add('hidden');// 显示通知showNotification('班费收取成功', 'success', `已收取班费 ${amount} 元`);});// 添加支出按钮addExpenseBtn.addEventListener('click', () => {addExpenseModal.classList.remove('hidden');});// 取消添加支出cancelAddExpenseBtn.addEventListener('click', () => {addExpenseModal.classList.add('hidden');});// 确认添加支出confirmAddExpenseBtn.addEventListener('click', () => {const amount = parseInt(document.getElementById('expenseAmount').value);const description = document.getElementById('expenseDescription').value || '班级支出';if (isNaN(amount) || amount <= 0) {showNotification('输入错误', 'error', '请输入有效的金额');return;}if (amount > gameState.classFund) {showNotification('余额不足', 'error', '班费余额不足,无法完成支出');return;}// 添加财务记录addFinanceRecord('expense', description, amount);// 更新班费gameState.classFund -= amount;// 添加事件addEvent('finance', `${description} (${amount}元)`, {type: 'expense',amount: amount,description: description});// 更新UIupdateUI();// 关闭弹窗addExpenseModal.classList.add('hidden');// 显示通知showNotification('支出记录成功', 'success', `已记录支出 ${amount} 元`);});// 关闭通知closeNotification.addEventListener('click', () => {notification.classList.remove('show');});// 学生搜索studentSearch.addEventListener('input', () => {renderStudents();});// 学生筛选studentFilter.addEventListener('change', () => {renderStudents();});// 尝试加载保存的游戏loadSavedGame();}// 初始化游戏状态function initializeGameState() {const region = regions[gameState.region];gameState.classFund = region.initialFund;gameState.currentWeek = 1;gameState.students = [];gameState.schedule = [];gameState.financeRecords = [];gameState.events = [];gameState.achievements = [];gameState.classStatus = {pressure: 0,satisfaction: 50};gameState.isGameOver = false;// 添加初始财务记录addFinanceRecord('income', '初始班费', region.initialFund);// 添加初始事件addEvent('system', `在${region.name}开始教学工作`, {region: gameState.region});}// 生成学生function generateStudents() {const region = regions[gameState.region];const studentCount = region.studentCount;// 学生名字池const firstNames = ["张", "李", "王", "刘", "陈", "杨", "赵", "黄", "周", "吴","徐", "孙", "胡", "朱", "高", "林", "何", "郭", "马", "罗"];const lastNames = ["伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "军","洋", "勇", "艳", "杰", "娟", "涛", "明", "超", "秀兰", "霞"];// 学生性格特点const personalities = [{ name: "勤奋", pressureModifier: 0.8, performanceModifier: 1.2 },{ name: "懒惰", pressureModifier: 1.2, performanceModifier: 0.8 },{ name: "开朗", pressureModifier: 0.9, performanceModifier: 1.0 },{ name: "内向", pressureModifier: 1.1, performanceModifier: 1.0 },{ name: "聪明", pressureModifier: 0.9, performanceModifier: 1.3 },{ name: "普通", pressureModifier: 1.0, performanceModifier: 1.0 },{ name: "调皮", pressureModifier: 0.8, performanceModifier: 0.9 },{ name: "安静", pressureModifier: 1.0, performanceModifier: 1.1 }];// 生成学生for (let i = 0; i < studentCount; i++) {const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];const personality = personalities[Math.floor(Math.random() * personalities.length)];// 随机生成基础属性const basePressure = Math.floor(Math.random() * 30) + 20; // 20-50const basePerformance = Math.floor(Math.random() * 40) + 30; // 30-70const pressureThreshold = Math.floor(Math.random() * 30) + 70; // 70-100// 应用性格修正const pressure = Math.min(100, Math.floor(basePressure * personality.pressureModifier * region.pressureModifier));const performance = Math.min(100, Math.floor(basePerformance * personality.performanceModifier));// 生成学生对象const student = {id: i + 1,name: firstName + lastName,gender: Math.random() > 0.5 ? "男" : "女",age: Math.floor(Math.random() * 3) + 13, // 13-15岁pressure: pressure,performance: performance,pressureThreshold: pressureThreshold,personality: personality.name,pressureHistory: [pressure],performanceHistory: [performance]};gameState.students.push(student);}// 计算初始班级压力calculateClassPressure();}// 初始化课程表function initializeSchedule() {// 预生成未来4周的课程表for (let i = 1; i <= 4; i++) {gameState.schedule.push({week: i,activity: null});}}// 初始化财务记录function initializeFinanceRecords() {// 已在initializeGameState中添加初始记录}// 更新UIfunction updateUI() {// 更新顶部状态栏document.getElementById('currentWeek').textContent = gameState.currentWeek;document.getElementById('classFund').textContent = gameState.classFund;// 更新班级概览document.getElementById('regionDisplay').textContent = regions[gameState.region].name;document.getElementById('studentCount').textContent = gameState.students.length;// 更新平均压力const avgPressure = calculateClassPressure();document.getElementById('avgPressureBar').style.width = `${avgPressure}%`;document.getElementById('avgPressureValue').textContent = `${Math.round(avgPressure)}%`;// 更新满意度document.getElementById('satisfactionBar').style.width = `${gameState.classStatus.satisfaction}%`;document.getElementById('satisfactionValue').textContent = `${Math.round(gameState.classStatus.satisfaction)}%`;// 更新班级状态updateClassStatus();// 更新本周活动显示updateWeeklyActivityDisplay();// 更新最近事件updateRecentEvents();// 更新压力图表updatePressureChart();// 更新本周建议updateWeeklySuggestion();}// 计算班级平均压力function calculateClassPressure() {if (gameState.students.length === 0) return 0;let totalPressure = 0;for (const student of gameState.students) {totalPressure += student.pressure;}const avgPressure = totalPressure / gameState.students.length;gameState.classStatus.pressure = avgPressure;return avgPressure;}// 更新班级状态function updateClassStatus() {const statusElement = document.getElementById('classStatus');const pressure = gameState.classStatus.pressure;const satisfaction = gameState.classStatus.satisfaction;// 根据压力和满意度综合评估班级状态if (pressure > 80 || satisfaction < 20) {statusElement.textContent = "危机";statusElement.className = "ml-1 px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800";} else if (pressure > 60 || satisfaction < 40) {statusElement.textContent = "不佳";statusElement.className = "ml-1 px-2 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-800";} else if (pressure > 40 || satisfaction < 60) {statusElement.textContent = "一般";statusElement.className = "ml-1 px-2 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800";} else {statusElement.textContent = "良好";statusElement.className = "ml-1 px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800";}}// 更新本周活动显示function updateWeeklyActivityDisplay() {const weeklyActivityElement = document.getElementById('weeklyActivity');const currentWeekSchedule = gameState.schedule.find(s => s.week === gameState.currentWeek);if (currentWeekSchedule && currentWeekSchedule.activity) {const activity = activities[currentWeekSchedule.activity];weeklyActivityElement.innerHTML = `<div class="flex items-center justify-center"><div class="w-10 h-10 ${activity.color} rounded-full flex items-center justify-center text-white mr-3"><i class="fa ${activity.icon}"></i></div><div class="text-left"><h4 class="font-bold">${activity.name}</h4><p class="text-sm text-gray-500">${activity.description}</p></div></div>`;} else {weeklyActivityElement.innerHTML = `<div class="flex flex-col items-center justify-center"><i class="fa fa-calendar-times-o text-gray-400 text-3xl mb-2"></i><p>尚未安排活动</p><button id="goToScheduleBtn" class="mt-2 text-primary hover:underline text-sm">去安排</button></div>`;// 添加按钮事件document.getElementById('goToScheduleBtn').addEventListener('click', () => {// 切换到课程安排页面navButtons.forEach(btn => btn.classList.remove('active', 'bg-blue-50', 'text-primary'));document.querySelector('[data-target="schedule"]').classList.add('active', 'bg-blue-50', 'text-primary');pageContents.forEach(page => page.classList.add('hidden'));document.getElementById('schedule').classList.remove('hidden');// 更新课程表renderSchedule();renderActivities();});}}// 更新最近事件function updateRecentEvents() {const recentEventsElement = document.getElementById('recentEvents');if (gameState.events.length === 0) {recentEventsElement.innerHTML = `<div class="text-center py-4 text-gray-500">暂无事件记录</div>`;return;}// 获取最近5个事件const recentEvents = gameState.events.slice(-5).reverse();let html = '';for (const event of recentEvents) {let icon = 'fa-info-circle';let iconColor = 'text-blue-500';switch (event.type) {case 'system':icon = 'fa-cog';iconColor = 'text-gray-500';break;case 'weekEnd':icon = 'fa-calendar-check-o';iconColor = 'text-green-500';break;case 'randomEvent':icon = 'fa-exclamation-triangle';iconColor = 'text-yellow-500';break;case 'finance':icon = event.data && event.data.type === 'income' ? 'fa-plus-circle' : 'fa-minus-circle';iconColor = event.data && event.data.type === 'income' ? 'text-green-500' : 'text-red-500';break;case 'activity':icon = 'fa-calendar';iconColor = 'text-purple-500';break;}html += `<div class="flex items-start"><i class="fa ${icon} ${iconColor} mt-1 mr-2"></i><div><p class="text-sm font-medium">${event.title}</p><p class="text-xs text-gray-500">第${event.week}周</p></div></div>`;}recentEventsElement.innerHTML = html;}// 更新压力图表function updatePressureChart() {const ctx = document.getElementById('pressureChart').getContext('2d');// 销毁旧图表if (window.pressureChart) {window.pressureChart.destroy();}// 准备数据const labels = [];const pressureData = [];const performanceData = [];// 获取最近8周的数据,如果有的话const weeksToShow = Math.min(8, gameState.currentWeek);for (let i = Math.max(1, gameState.currentWeek - weeksToShow + 1); i <= gameState.currentWeek; i++) {labels.push(`第${i}周`);// 查找该周的压力数据let weekEvent = gameState.events.find(e => e.type === 'weekEnd' && e.week === i);if (weekEvent && weekEvent.data) {pressureData.push(weekEvent.data.avgPressure);performanceData.push(weekEvent.data.avgPerformance);} else {// 如果没有数据,使用当前数据if (i === gameState.currentWeek) {pressureData.push(calculateClassPressure());// 计算平均表现let totalPerformance = 0;for (const student of gameState.students) {totalPerformance += student.performance;}performanceData.push(totalPerformance / gameState.students.length);} else {pressureData.push(null);performanceData.push(null);}}}// 创建图表window.pressureChart = new Chart(ctx, {type: 'line',data: {labels: labels,datasets: [{label: '平均压力',data: pressureData,borderColor: '#ef4444',backgroundColor: 'rgba(239, 68, 68, 0.1)',tension: 0.3,fill: true},{label: '平均表现',data: performanceData,borderColor: '#10b981',backgroundColor: 'rgba(16, 185, 129, 0.1)',tension: 0.3,fill: true}]},options: {responsive: true,maintainAspectRatio: false,scales: {y: {beginAtZero: true,max: 100,title: {display: true,text: '百分比 (%)'}}},plugins: {legend: {position: 'top',},tooltip: {mode: 'index',intersect: false}}}});}// 更新本周建议function updateWeeklySuggestion() {const suggestionElement = document.getElementById('weeklySuggestion');const pressure = gameState.classStatus.pressure;const satisfaction = gameState.classStatus.satisfaction;let suggestion = "";if (pressure > 70) {suggestion = "班级压力过高!建议本周安排放假或轻松的活动,如社团活动或公益活动,帮助学生缓解压力。";} else if (pressure > 50) {suggestion = "班级压力略高,建议减少考试和作业量,增加一些互动性强的教学活动。";} else if (satisfaction < 40) {suggestion = "班级满意度较低,建议增加与学生的沟通,了解他们的需求和意见,组织一些集体活动增强班级凝聚力。";} else if (gameState.classFund < 200) {suggestion = "班费余额较低,建议适当收取班费或减少不必要的开支,确保班级活动的正常开展。";} else {suggestion = "班级状态良好!可以考虑组织一次研学旅行或学科竞赛,进一步提升学生的学习兴趣和班级凝聚力。";}suggestionElement.textContent = suggestion;}// 渲染学生列表function renderStudents() {const container = document.getElementById('studentsContainer');const searchTerm = studentSearch.value.toLowerCase();const filter = studentFilter.value;// 筛选学生let filteredStudents = gameState.students;// 应用搜索if (searchTerm) {filteredStudents = filteredStudents.filter(student =>student.name.toLowerCase().includes(searchTerm));}// 应用筛选if (filter !== 'all') {switch (filter) {case 'high-pressure':filteredStudents = filteredStudents.filter(student => student.pressure > 70);break;case 'medium-pressure':filteredStudents = filteredStudents.filter(student => student.pressure >= 40 && student.pressure <= 70);break;case 'low-pressure':filteredStudents = filteredStudents.filter(student => student.pressure < 40);break;}}// 渲染学生卡片if (filteredStudents.length === 0) {container.innerHTML = `<div class="col-span-full text-center py-8 text-gray-500"><i class="fa fa-search text-4xl mb-3"></i><p>没有找到匹配的学生</p></div>`;return;}let html = '';for (const student of filteredStudents) {// 确定压力等级和颜色let pressureLevel = "低";let pressureColor = "bg-green-500";if (student.pressure > 70) {pressureLevel = "高";pressureColor = "bg-red-500";} else if (student.pressure > 40) {pressureLevel = "中";pressureColor = "bg-yellow-500";}// 确定表现等级和颜色let performanceLevel = "差";let performanceColor = "bg-red-500";if (student.performance >= 80) {performanceLevel = "优";performanceColor = "bg-green-500";} else if (student.performance >= 60) {performanceLevel = "良";performanceColor = "bg-blue-500";} else if (student.performance >= 40) {performanceLevel = "中";performanceColor = "bg-yellow-500";}html += `<div class="student-card bg-white rounded-lg shadow-md p-4 hover:shadow-lg transition-all cursor-pointer" data-student-id="${student.id}"><div class="flex justify-between items-start mb-3"><div><h3 class="font-bold text-gray-800">${student.name}</h3><p class="text-sm text-gray-500">${student.gender} | ${student.age}岁</p></div><div class="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center text-gray-600"><i class="fa fa-user"></i></div></div><div class="space-y-2"><div><div class="flex justify-between text-xs mb-1"><span>压力值</span><span>${Math.round(student.pressure)}% (${pressureLevel})</span></div><div class="w-full bg-gray-200 rounded-full h-2"><div class="pressure-bar ${pressureColor} h-2 rounded-full" style="width: ${student.pressure}%"></div></div></div><div><div class="flex justify-between text-xs mb-1"><span>学习表现</span><span>${Math.round(student.performance)}% (${performanceLevel})</span></div><div class="w-full bg-gray-200 rounded-full h-2"><div class="pressure-bar ${performanceColor} h-2 rounded-full" style="width: ${student.performance}%"></div></div></div></div><div class="mt-3 pt-3 border-t"><div class="flex justify-between text-xs"><span class="text-gray-600">性格特点</span><span class="font-medium">${student.personality}</span></div></div></div>`;}container.innerHTML = html;// 添加学生卡片点击事件document.querySelectorAll('.student-card').forEach(card => {card.addEventListener('click', () => {const studentId = parseInt(card.getAttribute('data-student-id'));showStudentDetail(studentId);});});}// 显示学生详情function showStudentDetail(studentId) {const student = gameState.students.find(s => s.id === studentId);if (!student) return;// 创建弹窗内容const modalContent = `<div class="bg-white rounded-lg shadow-xl p-6 max-w-md w-full animate-fade-in"><div class="flex justify-between items-center mb-4"><h2 class="text-xl font-bold text-gray-800">学生详情</h2><button id="closeStudentDetailBtn" class="text-gray-500 hover:text-gray-700"><i class="fa fa-times"></i></button></div><div class="flex items-center mb-6"><div class="w-16 h-16 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 mr-4"><i class="fa fa-user text-2xl"></i></div><div><h3 class="font-bold text-lg">${student.name}</h3><p class="text-gray-600">${student.gender} | ${student.age}岁</p></div></div><div class="space-y-4"><div><div class="flex justify-between text-sm mb-1"><span class="text-gray-600">压力值</span><span>${Math.round(student.pressure)}%</span></div><div class="w-full bg-gray-200 rounded-full h-2"><div class="pressure-bar ${student.pressure > 70 ? 'bg-red-500' : student.pressure > 40 ? 'bg-yellow-500' : 'bg-green-500'} h-2 rounded-full" style="width: ${student.pressure}%"></div></div></div><div><div class="flex justify-between text-sm mb-1"><span class="text-gray-600">学习表现</span><span>${Math.round(student.performance)}%</span></div><div class="w-full bg-gray-200 rounded-full h-2"><div class="pressure-bar ${student.performance >= 80 ? 'bg-green-500' : student.performance >= 60 ? 'bg-blue-500' : student.performance >= 40 ? 'bg-yellow-500' : 'bg-red-500'} h-2 rounded-full" style="width: ${student.performance}%"></div></div></div><div class="grid grid-cols-2 gap-4"><div><p class="text-sm text-gray-600 mb-1">性格特点</p><p class="font-medium">${student.personality}</p></div><div><p class="text-sm text-gray-600 mb-1">压力阈值</p><p class="font-medium">${student.pressureThreshold}%</p></div></div><div class="pt-4 border-t"><h4 class="font-medium mb-2">压力历史</h4><div class="h-32"><canvas id="studentPressureChart"></canvas></div></div></div><div class="mt-6 flex justify-end"><button id="counselStudentBtn" class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-all">谈心辅导</button></div></div>`;// 创建弹窗const modal = document.createElement('div');modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';modal.innerHTML = modalContent;document.body.appendChild(modal);// 关闭按钮事件document.getElementById('closeStudentDetailBtn').addEventListener('click', () => {modal.remove();});// 谈心辅导按钮事件document.getElementById('counselStudentBtn').addEventListener('click', () => {// 减少学生压力student.pressure = Math.max(0, student.pressure - 15);// 添加事件addEvent('student', `与${student.name}进行了谈心辅导`, {studentId: student.id,studentName: student.name,action: 'counsel',pressureReduction: 15});// 更新UIupdateUI();// 显示通知showNotification('谈心辅导成功', 'success', `${student.name}的压力得到了缓解`);// 关闭弹窗modal.remove();});// 创建学生压力图表const ctx = document.getElementById('studentPressureChart').getContext('2d');// 准备数据const labels = [];const pressureData = [];// 获取最近8周的数据const weeks = Math.min(8, student.pressureHistory.length);for (let i = Math.max(0, student.pressureHistory.length - weeks); i < student.pressureHistory.length; i++) {labels.push(`第${i + 1}周`);pressureData.push(student.pressureHistory[i]);}// 创建图表new Chart(ctx, {type: 'line',data: {labels: labels,datasets: [{label: '压力值',data: pressureData,borderColor: '#ef4444',backgroundColor: 'rgba(239, 68, 68, 0.1)',tension: 0.3,fill: true}]},options: {responsive: true,maintainAspectRatio: false,scales: {y: {beginAtZero: true,max: 100}}}});}// 渲染课程表function renderSchedule() {const container = document.getElementById('scheduleContainer');// 确保有未来4周的课程表ensureScheduleWeeks();let html = '';for (const week of gameState.schedule) {// 检查是否是当前周之前的周const isPastWeek = week.week < gameState.currentWeek;// 检查是否已安排活动let activityHtml = '';if (week.activity) {const activity = activities[week.activity];activityHtml = `<div class="flex items-center"><div class="w-8 h-8 ${activity.color} rounded-full flex items-center justify-center text-white mr-2"><i class="fa ${activity.icon}"></i></div><div><p class="font-medium">${activity.name}</p><p class="text-xs text-gray-500">${activity.description}</p></div></div>`;} else {activityHtml = `<div class="text-center py-2 text-gray-500"><p>尚未安排活动</p>${!isPastWeek ? '<button class="select-activity-btn mt-1 text-blue-500 hover:underline text-xs">选择活动</button>' : ''}</div>`;}html += `<div class="week-card bg-white rounded-lg shadow-md p-4 ${isPastWeek ? 'opacity-70' : ''}" data-week="${week.week}"><div class="flex justify-between items-center mb-3"><h3 class="font-bold text-gray-800">第${week.week}周</h3>${week.week === gameState.currentWeek ? '<span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">当前周</span>' : ''}</div><div class="border rounded-lg p-3 min-h-[100px]">${activityHtml}</div></div>`;}container.innerHTML = html;// 添加选择活动按钮事件document.querySelectorAll('.select-activity-btn').forEach(button => {button.addEventListener('click', (e) => {e.stopPropagation();// 获取周数const weekCard = button.closest('.week-card');const week = parseInt(weekCard.getAttribute('data-week'));// 显示活动选择面板document.querySelectorAll('.activity-card').forEach(card => {card.classList.add('cursor-pointer');card.addEventListener('click', function() {selectActivity(week, this.getAttribute('data-activity'));});});});});}// 确保有未来4周的课程表function ensureScheduleWeeks() {const currentMaxWeek = Math.max(...gameState.schedule.map(s => s.week), 0);const neededWeeks = Math.max(4, gameState.currentWeek + 3);for (let i = currentMaxWeek + 1; i <= neededWeeks; i++) {gameState.schedule.push({week: i,activity: null});}}// 渲染活动列表function renderActivities() {const container = document.getElementById('activitiesList');let html = '';for (const [key, activity] of Object.entries(activities)) {html += `<div class="activity-card p-3 border rounded-lg hover:bg-blue-50 transition-all" data-activity="${key}"><div class="flex items-center"><div class="w-10 h-10 ${activity.color} rounded-full flex items-center justify-center text-white mr-3"><i class="fa ${activity.icon}"></i></div><div class="flex-1"><h4 class="font-medium">${activity.name}</h4><p class="text-xs text-gray-600">${activity.description}</p></div></div><div class="mt-2 grid grid-cols-2 gap-2 text-xs"><div class="flex items-center"><i class="fa fa-money text-green-500 mr-1"></i><span>${activity.cost > 0 ? `花费: ${activity.cost}元` : '免费'}</span></div><div class="flex items-center"><i class="fa fa-heartbeat ${activity.pressureEffect > 0 ? 'text-red-500' : 'text-green-500'} mr-1"></i><span>压力: ${activity.pressureEffect > 0 ? '+' : ''}${activity.pressureEffect}%</span></div></div></div>`;}container.innerHTML = html;}// 选择活动function selectActivity(week, activityKey) {const activity = activities[activityKey];// 检查是否是过去的周if (week < gameState.currentWeek) {showNotification('无法安排', 'error', '不能为过去的周安排活动');return;}// 检查是否有足够的班费if (activity.cost > gameState.classFund) {showNotification('班费不足', 'error', `班费不足,需要${activity.cost}元`);return;}// 更新课程表const weekSchedule = gameState.schedule.find(s => s.week === week);if (weekSchedule) {weekSchedule.activity = activityKey;// 如果是当前周,立即应用效果if (week === gameState.currentWeek) {// 扣除费用if (activity.cost > 0) {gameState.classFund -= activity.cost;// 添加财务记录addFinanceRecord('expense', `${activity.name}费用`, activity.cost);}// 添加事件addEvent('activity', `安排了${activity.name}活动`, {activity: activityKey});// 更新UIupdateUI();}// 显示通知showNotification('活动安排成功', 'success', `已为第${week}周安排了${activity.name}活动`);// 重新渲染课程表renderSchedule();}}// 处理周活动效果function processWeekActivity(activityKey) {const activity = activities[activityKey];// 应用压力效果for (const student of gameState.students) {// 应用活动基础效果student.pressure = Math.max(0, Math.min(100, student.pressure + activity.pressureEffect));// 应用性格修正if (student.personality === "内向" && activity.pressureEffect > 0) {student.pressure = Math.min(100, student.pressure + 5);} else if (student.personality === "开朗" && activity.pressureEffect < 0) {student.pressure = Math.max(0, student.pressure - 5);}// 记录压力历史student.pressureHistory.push(student.pressure);// 更新学习表现// 压力过高或过低都会影响表现let performanceChange = 0;if (student.pressure > 80) {performanceChange = -5; // 压力过高影响表现} else if (student.pressure < 20) {performanceChange = -3; // 压力过低缺乏动力} else if (student.pressure >= 40 && student.pressure <= 60) {performanceChange = 3; // 适度压力促进表现}// 应用活动效果if (activityKey === "exam") {performanceChange += 5; // 考试周促进学习} else if (activityKey === "holiday") {performanceChange -= 2; // 放假可能影响学习状态}// 应用性格修正if (student.personality === "勤奋") {performanceChange += 2;} else if (student.personality === "懒惰") {performanceChange -= 2;}// 更新表现student.performance = Math.max(0, Math.min(100, student.performance + performanceChange));// 记录表现历史student.performanceHistory.push(student.performance);}// 应用满意度效果gameState.classStatus.satisfaction = Math.max(0, Math.min(100,gameState.classStatus.satisfaction + activity.satisfactionEffect));// 应用班费效果if (activity.fundEffect !== 0) {gameState.classFund = Math.max(0, gameState.classFund + activity.fundEffect);// 添加财务记录if (activity.fundEffect > 0) {addFinanceRecord('income', `${activity.name}收入`, activity.fundEffect);} else {addFinanceRecord('expense', `${activity.name}额外支出`, -activity.fundEffect);}}// 计算平均压力和表现let totalPressure = 0;let totalPerformance = 0;for (const student of gameState.students) {totalPressure += student.pressure;totalPerformance += student.performance;}const avgPressure = totalPressure / gameState.students.length;const avgPerformance = totalPerformance / gameState.students.length;// 添加周结束事件addEvent('weekEnd', `第${gameState.currentWeek}周结束,完成了${activity.name}活动`, {activity: activityKey,avgPressure: avgPressure,avgPerformance: avgPerformance});}// 渲染财务记录function renderFinanceRecords() {const container = document.getElementById('financeRecords');if (gameState.financeRecords.length === 0) {container.innerHTML = `<tr><td colspan="4" class="px-6 py-4 text-center text-gray-500">暂无财务记录</td></tr>`;return;}// 按日期排序,最新的在前const sortedRecords = [...gameState.financeRecords].sort((a, b) => {return new Date(b.date) - new Date(a.date);});let html = '';for (const record of sortedRecords) {const isIncome = record.type === 'income';const amountClass = isIncome ? 'text-green-600' : 'text-red-600';const amountSign = isIncome ? '+' : '-';html += `<tr><td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatDate(record.date)}</td><td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${isIncome ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">${isIncome ? '收入' : '支出'}</span></td><td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${record.description}</td><td class="px-6 py-4 whitespace-nowrap text-sm ${amountClass} text-right font-medium">${amountSign}${record.amount}元</td></tr>`;}container.innerHTML = html;// 更新财务概览document.getElementById('currentBalance').textContent = `${gameState.classFund}元`;// 计算总收入和支出const totalIncome = gameState.financeRecords.filter(r => r.type === 'income').reduce((sum, r) => sum + r.amount, 0);const totalExpense = gameState.financeRecords.filter(r => r.type === 'expense').reduce((sum, r) => sum + r.amount, 0);document.getElementById('totalIncome').textContent = `${totalIncome}元`;document.getElementById('totalExpense').textContent = `${totalExpense}元`;}// 添加财务记录function addFinanceRecord(type, description, amount) {gameState.financeRecords.push({type: type,description: description,amount: amount,date: new Date().toISOString()});}// 渲染事件记录function renderEvents() {const container = document.getElementById('eventsContainer');if (gameState.events.length === 0) {container.innerHTML = `<div class="text-center py-8 text-gray-500"><i class="fa fa-calendar-times-o text-4xl mb-3"></i><p>暂无事件记录</p></div>`;return;}// 按周排序,最新的在前const sortedEvents = [...gameState.events].sort((a, b) => {if (a.week !== b.week) {return b.week - a.week;}return new Date(b.date) - new Date(a.date);});let html = '';let currentWeek = -1;for (const event of sortedEvents) {// 如果是新的一周,添加周标题if (event.week !== currentWeek) {if (currentWeek !== -1) {html += `</div></div>`; // 关闭上周的内容}currentWeek = event.week;const isCurrentWeek = event.week === gameState.currentWeek;html += `<div class="mb-6"><h3 class="text-lg font-bold mb-3 flex items-center"><span class="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center text-white mr-2">${event.week}</span>第${event.week}周${isCurrentWeek ? '<span class="ml-2 px-2 py-0.5 bg-blue-100 text-blue-800 text-xs rounded-full">当前周</span>' : ''}</h3><div class="space-y-3 pl-10">`;}// 确定事件图标和颜色let icon = 'fa-info-circle';let iconColor = 'bg-blue-500';switch (event.type) {case 'system':icon = 'fa-cog';iconColor = 'bg-gray-500';break;case 'weekEnd':icon = 'fa-calendar-check-o';iconColor = 'bg-green-500';break;case 'randomEvent':icon = 'fa-exclamation-triangle';iconColor = 'bg-yellow-500';break;case 'finance':icon = event.data && event.data.type === 'income' ? 'fa-plus-circle' : 'fa-minus-circle';iconColor = event.data && event.data.type === 'income' ? 'bg-green-500' : 'bg-red-500';break;case 'activity':icon = 'fa-calendar';iconColor = 'bg-purple-500';break;case 'student':icon = 'fa-user';iconColor = 'bg-indigo-500';break;}// 添加事件内容html += `<div class="flex"><div class="w-6 h-6 ${iconColor} rounded-full flex items-center justify-center text-white text-xs mr-3 mt-0.5"><i class="fa ${icon}"></i></div><div class="bg-white rounded-lg shadow-sm p-3 flex-1"><p class="font-medium">${event.title}</p><p class="text-sm text-gray-500 mt-1">${formatDate(event.date)}</p>${event.data && event.type === 'weekEnd' ? `<div class="mt-2 pt-2 border-t text-sm"><div class="flex justify-between"><span class="text-gray-600">平均压力:</span><span>${Math.round(event.data.avgPressure)}%</span></div><div class="flex justify-between mt-1"><span class="text-gray-600">平均表现:</span><span>${Math.round(event.data.avgPerformance)}%</span></div></div>` : ''}</div></div>`;}// 关闭最后一周的内容if (currentWeek !== -1) {html += `</div></div>`;}container.innerHTML = html;}// 添加事件function addEvent(type, title, data = {}) {gameState.events.push({type: type,title: title,data: data,week: gameState.currentWeek,date: new Date().toISOString()});}// 渲染成就列表function renderAchievements() {const container = document.getElementById('achievementsContainer');let html = '';for (const achievement of achievements) {// 检查成就是否已解锁const isUnlocked = gameState.achievements.includes(achievement.id);html += `<div class="achievement-card bg-white rounded-lg shadow-md p-4 ${isUnlocked ? 'border-2 border-yellow-400' : 'opacity-60'}"><div class="flex items-center mb-3"><div class="w-10 h-10 ${achievement.iconColor} rounded-full flex items-center justify-center text-white mr-3"><i class="fa ${achievement.icon}"></i></div><div><h4 class="font-bold">${achievement.title}</h4><p class="text-xs text-gray-500">${achievement.description}</p></div></div><div class="flex justify-between items-center"><span class="text-xs text-gray-600">奖励</span><span class="text-sm font-medium text-green-600"><i class="fa fa-money mr-1"></i>${achievement.reward.fund}元</span></div><div class="mt-3 pt-3 border-t"><div class="flex justify-between items-center"><span class="text-xs text-gray-600">状态</span><span class="text-sm font-medium ${isUnlocked ? 'text-green-600' : 'text-gray-500'}">${isUnlocked ? '已解锁' : '未解锁'}</span></div></div></div>`;}container.innerHTML = html;}// 检查成就function checkAchievements() {for (const achievement of achievements) {// 如果成就已解锁,跳过if (gameState.achievements.includes(achievement.id)) continue;// 检查成就条件if (achievement.condition(gameState)) {// 解锁成就gameState.achievements.push(achievement.id);// 应用奖励if (achievement.reward.fund) {gameState.classFund += achievement.reward.fund;// 添加财务记录addFinanceRecord('income', `成就奖励: ${achievement.title}`, achievement.reward.fund);}// 添加事件addEvent('system', `解锁成就: ${achievement.title}`, {achievement: achievement.id});// 显示成就解锁通知showAchievementNotification(achievement);// 更新UIupdateUI();}}}// 显示成就解锁通知function showAchievementNotification(achievement) {// 创建成就通知元素const notification = document.createElement('div');notification.className = 'fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white rounded-lg shadow-xl p-6 z-50 max-w-md w-full achievement-unlock';notification.innerHTML = `<div class="text-center"><div class="w-16 h-16 ${achievement.iconColor} rounded-full flex items-center justify-center text-white mx-auto mb-4"><i class="fa ${achievement.icon} text-2xl"></i></div><h3 class="text-xl font-bold text-yellow-600 mb-2">成就解锁!</h3><h4 class="text-lg font-bold mb-2">${achievement.title}</h4><p class="text-gray-600 mb-4">${achievement.description}</p><div class="text-green-600 font-bold mb-4"><i class="fa fa-money mr-2"></i>奖励: ${achievement.reward.fund}元</div><button id="closeAchievementNotification" class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-all">太棒了!</button></div>`;document.body.appendChild(notification);// 添加关闭按钮事件document.getElementById('closeAchievementNotification').addEventListener('click', () => {notification.remove();});// 3秒后自动关闭setTimeout(() => {notification.classList.add('opacity-0', 'scale-95');setTimeout(() => {notification.remove();}, 300);}, 5000);}// 检查随机事件function checkRandomEvent() {// 30%的概率触发随机事件if (Math.random() < 0.3) {// 随机选择一个事件const event = randomEvents[Math.floor(Math.random() * randomEvents.length)];// 显示事件弹窗showEventModal(event);}}// 显示事件弹窗function showEventModal(event) {// 设置事件内容document.getElementById('eventTitle').textContent = event.title;document.getElementById('eventDescription').textContent = event.description;document.getElementById('eventIcon').className = `w-12 h-12 ${event.iconColor} rounded-full flex items-center justify-center text-white mr-4`;document.getElementById('eventIcon').innerHTML = `<i class="fa ${event.icon} text-xl"></i>`;// 生成选项const optionsContainer = document.getElementById('eventOptions');let html = '';for (const option of event.options) {html += `<button class="event-option w-full text-left p-3 border rounded-lg hover:bg-blue-50 transition-all"data-effects='${JSON.stringify(option.effects)}'data-result="${option.result}"><p class="font-medium">${option.text}</p><div class="mt-2 flex flex-wrap gap-2">${option.effects.pressure !== 0 ? `<span class="px-2 py-1 bg-${option.effects.pressure > 0 ? 'red' : 'green'}-100 text-${option.effects.pressure > 0 ? 'red' : 'green'}-800 text-xs rounded-full">压力: ${option.effects.pressure > 0 ? '+' : ''}${option.effects.pressure}%</span>` : ''}${option.effects.satisfaction !== 0 ? `<span class="px-2 py-1 bg-${option.effects.satisfaction > 0 ? 'green' : 'red'}-100 text-${option.effects.satisfaction > 0 ? 'green' : 'red'}-800 text-xs rounded-full">满意度: ${option.effects.satisfaction > 0 ? '+' : ''}${option.effects.satisfaction}%</span>` : ''}${option.effects.fund !== 0 ? `<span class="px-2 py-1 bg-${option.effects.fund > 0 ? 'green' : 'red'}-100 text-${option.effects.fund > 0 ? 'green' : 'red'}-800 text-xs rounded-full">班费: ${option.effects.fund > 0 ? '+' : ''}${option.effects.fund}元</span>` : ''}</div></button>`;}optionsContainer.innerHTML = html;// 显示弹窗eventModal.classList.remove('hidden');// 添加选项点击事件document.querySelectorAll('.event-option').forEach(option => {option.addEventListener('click', () => {const effects = JSON.parse(option.getAttribute('data-effects'));const result = option.getAttribute('data-result');// 应用效果// 压力效果if (effects.pressure) {for (const student of gameState.students) {student.pressure = Math.max(0, Math.min(100, student.pressure + effects.pressure));}calculateClassPressure();}// 满意度效果if (effects.satisfaction) {gameState.classStatus.satisfaction = Math.max(0, Math.min(100,gameState.classStatus.satisfaction + effects.satisfaction));}// 班费效果if (effects.fund) {gameState.classFund = Math.max(0, gameState.classFund + effects.fund);// 添加财务记录if (effects.fund > 0) {addFinanceRecord('income', `事件收入: ${event.title}`, effects.fund);} else {addFinanceRecord('expense', `事件支出: ${event.title}`, -effects.fund);}}// 添加事件addEvent('randomEvent', `${event.title} - ${result}`, {eventId: event.id,choice: option.querySelector('p').textContent,result: result,effects: effects});// 更新UIupdateUI();// 关闭弹窗eventModal.classList.add('hidden');// 显示通知showNotification('事件处理完成', 'info', result);});});}// 检查游戏结束条件function checkGameOver() {// 检查班级满意度是否为0if (gameState.classStatus.satisfaction <= 0) {gameOver('班级满意度降至0,你被学校解雇了!');return;}// 检查是否所有学生压力都超过阈值let highPressureCount = 0;for (const student of gameState.students) {if (student.pressure >= student.pressureThreshold) {highPressureCount++;}}if (highPressureCount >= gameState.students.length * 0.8) {gameOver('太多学生压力过大,家长投诉导致你被调职!');return;}// 检查是否完成24周教学if (gameState.currentWeek > 24) {gameOver('恭喜你成功完成了一学期的教学工作!', true);return;}}// 游戏结束function gameOver(message, isVictory = false) {gameState.isGameOver = true;// 创建游戏结束弹窗const modal = document.createElement('div');modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';modal.innerHTML = `<div class="bg-white rounded-lg shadow-xl p-8 max-w-md w-full animate-fade-in"><div class="text-center"><div class="w-16 h-16 ${isVictory ? 'bg-green-500' : 'bg-red-500'} rounded-full flex items-center justify-center text-white mx-auto mb-4"><i class="fa ${isVictory ? 'fa-trophy' : 'fa-times-circle'} text-2xl"></i></div><h2 class="text-2xl font-bold mb-4">${isVictory ? '游戏胜利!' : '游戏结束'}</h2><p class="text-gray-600 mb-6">${message}</p><div class="space-y-3 mb-6"><div class="flex justify-between"><span class="text-gray-600">完成周数:</span><span class="font-medium">${gameState.currentWeek - 1}周</span></div><div class="flex justify-between"><span class="text-gray-600">最终班费:</span><span class="font-medium">${gameState.classFund}元</span></div><div class="flex justify-between"><span class="text-gray-600">解锁成就:</span><span class="font-medium">${gameState.achievements.length}/${achievements.length}</span></div><div class="flex justify-between"><span class="text-gray-600">班级满意度:</span><span class="font-medium">${Math.round(gameState.classStatus.satisfaction)}%</span></div></div><div class="flex justify-center space-x-4"><button id="restartGameOverBtn" class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-all">重新开始</button><button id="saveGameOverBtn" class="px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg transition-all">保存游戏</button></div></div></div>`;document.body.appendChild(modal);// 添加按钮事件document.getElementById('restartGameOverBtn').addEventListener('click', () => {restartGameBtn.click();});document.getElementById('saveGameOverBtn').addEventListener('click', () => {saveGameBtn.click();showNotification('游戏已保存', 'success', '你的游戏进度已成功保存');});}// 显示通知function showNotification(title, type, message) {// 设置通知内容document.getElementById('notificationTitle').textContent = title;document.getElementById('notificationMessage').textContent = message;// 设置图标const iconElement = document.getElementById('notificationIcon');const iconIElement = document.getElementById('notificationIconI');iconElement.className = 'w-8 h-8 rounded-full flex items-center justify-center mr-3';iconIElement.className = 'fa';switch (type) {case 'success':iconElement.classList.add('bg-green-500', 'text-white');iconIElement.classList.add('fa-check');break;case 'error':iconElement.classList.add('bg-red-500', 'text-white');iconIElement.classList.add('fa-times');break;case 'warning':iconElement.classList.add('bg-yellow-500', 'text-white');iconIElement.classList.add('fa-exclamation');break;default:iconElement.classList.add('bg-blue-500', 'text-white');iconIElement.classList.add('fa-info');}// 显示通知notification.classList.add('show');// 3秒后自动隐藏setTimeout(() => {notification.classList.remove('show');}, 3000);}// 格式化日期function formatDate(dateString) {const date = new Date(dateString);return `${date.getMonth() + 1}月${date.getDate()}日`;}// 加载保存的游戏function loadSavedGame() {const savedGame = localStorage.getItem('teacherSimulatorSave');if (savedGame) {// 询问是否加载保存的游戏if (confirm('检测到保存的游戏进度,是否加载?')) {try {gameState = JSON.parse(savedGame);// 隐藏设置弹窗,显示游戏界面setupModal.classList.add('hidden');gameContainer.classList.remove('hidden');// 更新UIupdateUI();// 显示通知showNotification('游戏加载成功', 'success', '已成功加载保存的游戏进度');} catch (error) {console.error('加载游戏失败:', error);showNotification('加载失败', 'error', '无法加载保存的游戏进度');}}}}// 初始化游戏window.addEventListener('DOMContentLoaded', initGame);</script></body></html>```2 行未改动3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515562 行未改动<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>塔防游戏 - 网页版</title><!-- Tailwind CSS v3 --><script src="https://cdn.tailwindcss.com"></script><!-- Font Awesome --><link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet"><script>tailwind.config = {theme: {extend: {colors: {primary: '#4CAF50',secondary: '#FFC107',danger: '#F44336',info: '#2196F3',dark: '#2C3E50',light: '#ECF0F1'},fontFamily: {sans: ['Inter', 'system-ui', 'sans-serif'],},animation: {'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',}}}}</script><style type="text/tailwindcss">@layer utilities {.text-shadow {text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);}.tower-shadow {filter: drop-shadow(0px 4px 6px rgba(0, 0, 0, 0.3));}.enemy-shadow {filter: drop-shadow(0px 2px 4px rgba(0, 0, 0, 0.2));}.rain-effect {background-image: linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.7) 100%);animation: rain 0.8s linear infinite;}@keyframes rain {0% { transform: translateY(-100%); opacity: 0; }50% { opacity: 0.5; }100% { transform: translateY(100%); opacity: 0; }}}</style><style>body {overflow: hidden;background-color: #1a1a2e;}#gameCanvas {background-color: #2c3e50;background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="%232c3e50"/><path d="M0,50 L100,50 M50,0 L50,100" stroke="%2334495e" stroke-width="0.5"/></svg>');background-size: 50px 50px;}.tower {cursor: pointer;transition: all 0.2s ease;}.tower:hover {transform: translateY(-5px);}.enemy {position: absolute;transition: transform 0.1s linear;}.projectile {position: absolute;width: 8px;height: 8px;border-radius: 50%;background-color: #FFC107;z-index: 10;}.explosion {position: absolute;width: 30px;height: 30px;border-radius: 50%;background-color: #F44336;opacity: 0.7;animation: explode 0.5s ease-out forwards;z-index: 20;}@keyframes explode {0% { transform: scale(0); opacity: 1; }100% { transform: scale(2); opacity: 0; }}.range-indicator {position: absolute;border: 2px dashed rgba(255, 255, 255, 0.5);border-radius: 50%;pointer-events: none;z-index: 5;}.health-bar {position: absolute;width: 100%;height: 4px;background-color: #e74c3c;top: -8px;left: 0;border-radius: 2px;}.health-bar-fill {height: 100%;background-color: #2ecc71;border-radius: 2px;transition: width 0.2s ease;}.weather-overlay {position: absolute;top: 0;left: 0;width: 100%;height: 100%;pointer-events: none;z-index: 15;}.tower-info {position: absolute;background-color: rgba(0, 0, 0, 0.8);color: white;padding: 8px;border-radius: 4px;font-size: 12px;z-index: 25;pointer-events: none;opacity: 0;transition: opacity 0.2s ease;}.tower:hover + .tower-info {opacity: 1;}.wave-notification {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);background-color: rgba(0, 0, 0, 0.8);color: white;padding: 20px 40px;border-radius: 8px;font-size: 24px;font-weight: bold;z-index: 100;animation: wave-notification 2s ease-out forwards;}@keyframes wave-notification {0% { opacity: 0; transform: translate(-50%, -50%) scale(0.5); }20% { opacity: 1; transform: translate(-50%, -50%) scale(1.1); }30% { transform: translate(-50%, -50%) scale(1); }80% { opacity: 1; }100% { opacity: 0; }}</style></head><body class="bg-gray-900 text-white"><div class="flex flex-col h-screen"><!-- 顶部信息栏 --><div class="bg-dark p-4 flex justify-between items-center shadow-lg"><div class="flex items-center space-x-6"><div class="flex items-center"><i class="fa fa-coins text-secondary text-2xl mr-2"></i><span id="gold" class="text-xl font-bold">500</span></div><div class="flex items-center"><i class="fa fa-heart text-danger text-2xl mr-2"></i><span id="lives" class="text-xl font-bold">20</span></div><div class="flex items-center"><i class="fa fa-refresh text-info text-2xl mr-2"></i><span id="wave" class="text-xl font-bold">1</span></div></div><div class="flex items-center space-x-4"><div class="flex items-center"><label for="gameSpeed" class="mr-2">速度:</label><input type="range" id="gameSpeed" min="0.5" max="2" step="0.5" value="1" class="w-24"><span id="speedValue" class="ml-2">1x</span></div><button id="startWave" class="bg-primary hover:bg-green-600 text-white font-bold py-2 px-4 rounded-lg transition-all flex items-center"><i class="fa fa-play mr-2"></i> 开始波次</button><button id="pauseGame" class="bg-info hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-lg transition-all flex items-center"><i class="fa fa-pause mr-2"></i> 暂停</button><button id="restartGame" class="bg-danger hover:bg-red-600 text-white font-bold py-2 px-4 rounded-lg transition-all flex items-center"><i class="fa fa-refresh mr-2"></i> 重新开始</button></div></div><!-- 主要游戏区域 --><div class="flex flex-1 overflow-hidden"><!-- 左侧防御塔选择面板 --><div class="w-64 bg-dark p-4 shadow-lg overflow-y-auto"><h2 class="text-xl font-bold mb-4 text-center border-b border-gray-700 pb-2">防御塔</h2><div class="space-y-4"><!-- 防御塔类型1 --><div class="tower bg-gray-800 rounded-lg p-3 flex flex-col items-center hover:bg-gray-700 transition-all"><div class="tower-icon w-16 h-16 bg-primary rounded-full flex items-center justify-center mb-2 tower-shadow"><i class="fa fa-crosshairs text-2xl"></i></div><h3 class="font-bold">基础塔</h3><div class="flex justify-between w-full mt-2 text-sm"><span>伤害: 10</span><span>范围: 100</span></div><div class="flex justify-between w-full mt-1 text-sm"><span>攻速: 快</span><span class="text-secondary"><i class="fa fa-coins mr-1"></i>50</span></div><button class="tower-btn mt-2 w-full bg-primary hover:bg-green-600 text-white py-1 px-2 rounded transition-all" data-tower-type="basic">选择</button></div><!-- 防御塔类型2 --><div class="tower bg-gray-800 rounded-lg p-3 flex flex-col items-center hover:bg-gray-700 transition-all"><div class="tower-icon w-16 h-16 bg-secondary rounded-full flex items-center justify-center mb-2 tower-shadow"><i class="fa fa-bomb text-2xl"></i></div><h3 class="font-bold">爆破塔</h3><div class="flex justify-between w-full mt-2 text-sm"><span>伤害: 30</span><span>范围: 80</span></div><div class="flex justify-between w-full mt-1 text-sm"><span>攻速: 慢</span><span class="text-secondary"><i class="fa fa-coins mr-1"></i>100</span></div><button class="tower-btn mt-2 w-full bg-secondary hover:bg-yellow-600 text-white py-1 px-2 rounded transition-all" data-tower-type="explosive">选择</button></div><!-- 防御塔类型3 --><div class="tower bg-gray-800 rounded-lg p-3 flex flex-col items-center hover:bg-gray-700 transition-all"><div class="tower-icon w-16 h-16 bg-info rounded-full flex items-center justify-center mb-2 tower-shadow"><i class="fa fa-bolt text-2xl"></i></div><h3 class="font-bold">电塔</h3><div class="flex justify-between w-full mt-2 text-sm"><span>伤害: 15</span><span>范围: 120</span></div><div class="flex justify-between w-full mt-1 text-sm"><span>攻速: 中</span><span class="text-secondary"><i class="fa fa-coins mr-1"></i>150</span></div><button class="tower-btn mt-2 w-full bg-info hover:bg-blue-600 text-white py-1 px-2 rounded transition-all" data-tower-type="electric">选择</button></div></div><h2 class="text-xl font-bold my-4 text-center border-b border-gray-700 pb-2">天气效果</h2><div class="space-y-2"><div class="flex items-center justify-between"><span>天气状态:</span><span id="weatherStatus" class="font-bold">晴天</span></div><div class="flex items-center justify-between"><span>效果:</span><span id="weatherEffect" class="text-sm">无特殊效果</span></div></div><h2 class="text-xl font-bold my-4 text-center border-b border-gray-700 pb-2">游戏统计</h2><div class="space-y-2"><div class="flex items-center justify-between"><span>消灭敌人:</span><span id="enemiesKilled">0</span></div><div class="flex items-center justify-between"><span>建造塔数:</span><span id="towersBuilt">0</span></div><div class="flex items-center justify-between"><span>游戏时间:</span><span id="gameTime">00:00</span></div></div></div><!-- 游戏画布区域 --><div class="flex-1 relative"><canvas id="gameCanvas" class="absolute top-0 left-0 w-full h-full"></canvas><div id="weatherOverlay" class="weather-overlay"></div><div id="towerInfo" class="tower-info"></div><!-- 游戏结束/胜利界面 --><div id="gameOver" class="absolute inset-0 bg-black bg-opacity-80 flex items-center justify-center z-50 hidden"><div class="bg-dark p-8 rounded-lg shadow-2xl text-center max-w-md"><h2 id="gameOverTitle" class="text-3xl font-bold mb-4">游戏结束</h2><p id="gameOverMessage" class="text-xl mb-6">你未能阻止敌人的进攻!</p><div class="space-y-4"><div class="flex justify-between"><span>波次:</span><span id="finalWave">1</span></div><div class="flex justify-between"><span>消灭敌人:</span><span id="finalEnemiesKilled">0</span></div><div class="flex justify-between"><span>建造塔数:</span><span id="finalTowersBuilt">0</span></div></div><button id="playAgain" class="mt-6 bg-primary hover:bg-green-600 text-white font-bold py-3 px-6 rounded-lg transition-all text-lg">再玩一次</button></div></div></div></div></div><script>// 游戏常量const CANVAS_WIDTH = 1200;const CANVAS_HEIGHT = 600;const GRID_SIZE = 50;const PATH_COLOR = '#34495e';const GRASS_COLOR = '#27ae60';const TOWER_PLACE_COLOR = 'rgba(39, 174, 96, 0.5)';const TOWER_INVALID_COLOR = 'rgba(231, 76, 60, 0.5)';// 游戏状态let gameState = {gold: 500,lives: 20,wave: 1,gameSpeed: 1,isPaused: false,isWaveActive: false,selectedTowerType: null,towers: [],enemies: [],projectiles: [],explosions: [],weather: 'sunny', // sunny, rainy, snowyenemiesKilled: 0,towersBuilt: 0,gameTime: 0,gameTimeInterval: null,lastUpdateTime: 0,waveEnemies: 0,waveEnemiesSpawned: 0,waveEnemyLimit: 10,waveSpawnTimer: 0,waveSpawnInterval: 1000, // 毫秒gameOver: false};// 防御塔配置const towerTypes = {basic: {name: '基础塔',cost: 50,damage: 10,range: 100,fireRate: 1000, // 毫秒color: '#4CAF50',projectileColor: '#FFC107',projectileSpeed: 5,description: '基础防御塔,攻速快,伤害一般'},explosive: {name: '爆破塔',cost: 100,damage: 30,range: 80,fireRate: 2000, // 毫秒color: '#FFC107',projectileColor: '#F44336',projectileSpeed: 3,splashRadius: 40,description: '爆破塔,伤害高,范围攻击,攻速慢'},electric: {name: '电塔',cost: 150,damage: 15,range: 120,fireRate: 1500, // 毫秒color: '#2196F3',projectileColor: '#FFEB3B',projectileSpeed: 4,chainTargets: 2,description: '电塔,攻击范围大,可攻击多个目标'}};// 敌人配置const enemyTypes = {basic: {name: '普通敌人',health: 100,speed: 1,reward: 10,color: '#e74c3c',size: 20},fast: {name: '快速敌人',health: 50,speed: 2,reward: 15,color: '#9b59b6',size: 15},tank: {name: '坦克敌人',health: 300,speed: 0.5,reward: 30,color: '#8e44ad',size: 30}};// 天气效果配置const weatherEffects = {sunny: {name: '晴天',effect: '无特殊效果',towerModifier: { range: 1, damage: 1, fireRate: 1 },enemyModifier: { speed: 1, health: 1 }},rainy: {name: '雨天',effect: '减慢敌人速度,降低塔攻击范围',towerModifier: { range: 0.8, damage: 1, fireRate: 1 },enemyModifier: { speed: 0.8, health: 1 }},snowy: {name: '雪天',effect: '减慢敌人速度,降低塔攻击速度',towerModifier: { range: 1, damage: 1, fireRate: 0.8 },enemyModifier: { speed: 0.7, health: 1.1 }}};// 游戏路径点const pathPoints = [{ x: 0, y: 300 },{ x: 200, y: 300 },{ x: 200, y: 150 },{ x: 400, y: 150 },{ x: 400, y: 450 },{ x: 600, y: 450 },{ x: 600, y: 150 },{ x: 800, y: 150 },{ x: 800, y: 300 },{ x: 1000, y: 300 },{ x: 1000, y: 450 },{ x: 1200, y: 450 }];// 获取DOM元素const canvas = document.getElementById('gameCanvas');const ctx = canvas.getContext('2d');const goldDisplay = document.getElementById('gold');const livesDisplay = document.getElementById('lives');const waveDisplay = document.getElementById('wave');const startWaveBtn = document.getElementById('startWave');const pauseGameBtn = document.getElementById('pauseGame');const restartGameBtn = document.getElementById('restartGame');const gameSpeedSlider = document.getElementById('gameSpeed');const speedValueDisplay = document.getElementById('speedValue');const weatherStatusDisplay = document.getElementById('weatherStatus');const weatherEffectDisplay = document.getElementById('weatherEffect');const enemiesKilledDisplay = document.getElementById('enemiesKilled');const towersBuiltDisplay = document.getElementById('towersBuilt');const gameTimeDisplay = document.getElementById('gameTime');const gameOverScreen = document.getElementById('gameOver');const gameOverTitle = document.getElementById('gameOverTitle');const gameOverMessage = document.getElementById('gameOverMessage');const finalWaveDisplay = document.getElementById('finalWave');const finalEnemiesKilledDisplay = document.getElementById('finalEnemiesKilled');const finalTowersBuiltDisplay = document.getElementById('finalTowersBuilt');const playAgainBtn = document.getElementById('playAgain');const towerButtons = document.querySelectorAll('.tower-btn');// 初始化画布function initCanvas() {canvas.width = CANVAS_WIDTH;canvas.height = CANVAS_HEIGHT;// 设置画布大小以匹配容器function resizeCanvas() {const container = canvas.parentElement;canvas.style.width = container.clientWidth + 'px';canvas.style.height = container.clientHeight + 'px';}resizeCanvas();window.addEventListener('resize', resizeCanvas);}// 初始化游戏function initGame() {initCanvas();setupEventListeners();startGameTimer();updateWeatherDisplay();gameLoop();}// 设置事件监听器function setupEventListeners() {// 塔选择按钮towerButtons.forEach(button => {button.addEventListener('click', () => {const towerType = button.getAttribute('data-tower-type');selectTowerType(towerType);});});// 画布点击事件 - 放置塔canvas.addEventListener('click', handleCanvasClick);// 开始波次按钮startWaveBtn.addEventListener('click', startWave);// 暂停/继续游戏按钮pauseGameBtn.addEventListener('click', togglePause);// 重新开始按钮restartGameBtn.addEventListener('click', restartGame);// 游戏速度滑块gameSpeedSlider.addEventListener('input', updateGameSpeed);// 再玩一次按钮playAgainBtn.addEventListener('click', restartGame);}// 选择塔类型function selectTowerType(type) {gameState.selectedTowerType = type;// 更新UI显示选中状态towerButtons.forEach(btn => {if (btn.getAttribute('data-tower-type') === type) {btn.classList.add('ring-2', 'ring-white');} else {btn.classList.remove('ring-2', 'ring-white');}});}// 处理画布点击事件function handleCanvasClick(event) {if (gameState.isPaused || gameState.gameOver) return;const rect = canvas.getBoundingClientRect();const x = (event.clientX - rect.left) * (canvas.width / rect.width);const y = (event.clientY - rect.top) * (canvas.height / rect.height);// 如果选择了塔类型,尝试放置塔if (gameState.selectedTowerType) {placeTower(x, y);}}// 放置塔function placeTower(x, y) {const towerType = gameState.selectedTowerType;const towerConfig = towerTypes[towerType];// 检查是否有足够的金币if (gameState.gold < towerConfig.cost) {showNotification('金币不足!', 'error');return;}// 检查位置是否有效(不在路径上,不与其他塔重叠)if (!isValidTowerPosition(x, y)) {showNotification('无法在此位置建造塔!', 'error');return;}// 创建新塔const newTower = {type: towerType,x: x,y: y,lastFired: 0,target: null,...towerConfig};// 应用天气效果applyWeatherEffectsToTower(newTower);// 添加到塔列表gameState.towers.push(newTower);// 扣除金币gameState.gold -= towerConfig.cost;// 更新统计gameState.towersBuilt++;// 更新UIupdateUI();showNotification(`建造了 ${towerConfig.name}!`, 'success');}// 检查塔位置是否有效function isValidTowerPosition(x, y) {// 检查是否在路径上if (isPointOnPath(x, y)) {return false;}// 检查是否与其他塔重叠for (const tower of gameState.towers) {const distance = Math.sqrt(Math.pow(x - tower.x, 2) + Math.pow(y - tower.y, 2));if (distance < 40) { // 塔的半径return false;}}return true;}// 检查点是否在路径上function isPointOnPath(x, y) {// 简化版:检查点是否靠近路径点之间的线段for (let i = 0; i < pathPoints.length - 1; i++) {const p1 = pathPoints[i];const p2 = pathPoints[i + 1];// 检查点到线段的距离const distance = distancePointToLine(x, y, p1.x, p1.y, p2.x, p2.y);if (distance < 30) { // 路径宽度return true;}}return false;}// 计算点到线段的距离function distancePointToLine(x, y, x1, y1, x2, y2) {const A = x - x1;const B = y - y1;const C = x2 - x1;const D = y2 - y1;const dot = A * C + B * D;const lenSq = C * C + D * D;let param = -1;if (lenSq !== 0) {param = dot / lenSq;}let xx, yy;if (param < 0) {xx = x1;yy = y1;} else if (param > 1) {xx = x2;yy = y2;} else {xx = x1 + param * C;yy = y1 + param * D;}const dx = x - xx;const dy = y - yy;return Math.sqrt(dx * dx + dy * dy);}// 开始新波次function startWave() {if (gameState.isWaveActive || gameState.isPaused || gameState.gameOver) return;gameState.isWaveActive = true;gameState.waveEnemies = 0;gameState.waveEnemiesSpawned = 0;gameState.waveEnemyLimit = 10 + (gameState.wave * 2); // 每波增加2个敌人gameState.waveSpawnTimer = 0;// 显示波次通知showWaveNotification(`第 ${gameState.wave} 波`);// 更新按钮状态startWaveBtn.disabled = true;startWaveBtn.classList.add('opacity-50', 'cursor-not-allowed');// 随机改变天气if (Math.random() < 0.3) { // 30% 几率改变天气const weathers = ['sunny', 'rainy', 'snowy'];gameState.weather = weathers[Math.floor(Math.random() * weathers.length)];updateWeatherDisplay();}}// 生成敌人function spawnEnemy() {if (gameState.waveEnemiesSpawned >= gameState.waveEnemyLimit) return;// 根据波次决定敌人类型let enemyType = 'basic';const rand = Math.random();if (gameState.wave >= 3 && rand < 0.3) {enemyType = 'fast';} else if (gameState.wave >= 5 && rand < 0.2) {enemyType = 'tank';}const enemyConfig = enemyTypes[enemyType];// 创建新敌人const newEnemy = {type: enemyType,x: pathPoints[0].x,y: pathPoints[0].y,health: enemyConfig.health,maxHealth: enemyConfig.health,speed: enemyConfig.speed,reward: enemyConfig.reward,pathIndex: 0,...enemyConfig};// 应用天气效果applyWeatherEffectsToEnemy(newEnemy);// 添加到敌人列表gameState.enemies.push(newEnemy);gameState.waveEnemiesSpawned++;}// 应用天气效果到塔function applyWeatherEffectsToTower(tower) {const weatherEffect = weatherEffects[gameState.weather];// 应用修改器tower.range *= weatherEffect.towerModifier.range;tower.damage *= weatherEffect.towerModifier.damage;tower.fireRate *= weatherEffect.towerModifier.fireRate;}// 应用天气效果到敌人function applyWeatherEffectsToEnemy(enemy) {const weatherEffect = weatherEffects[gameState.weather];// 应用修改器enemy.speed *= weatherEffect.enemyModifier.speed;enemy.health *= weatherEffect.enemyModifier.health;enemy.maxHealth = enemy.health; // 更新最大生命值}// 更新天气显示function updateWeatherDisplay() {const weatherEffect = weatherEffects[gameState.weather];weatherStatusDisplay.textContent = weatherEffect.name;weatherEffectDisplay.textContent = weatherEffect.effect;// 更新天气覆盖层const weatherOverlay = document.getElementById('weatherOverlay');weatherOverlay.className = 'weather-overlay';if (gameState.weather === 'rainy') {weatherOverlay.classList.add('rain-effect');} else if (gameState.weather === 'snowy') {weatherOverlay.classList.add('snow-effect');}}// 塔攻击逻辑function towerAttack(tower, currentTime) {// 检查是否可以开火if (currentTime - tower.lastFired < tower.fireRate) return;// 寻找目标const target = findTarget(tower);if (!target) return;// 创建投射物createProjectile(tower, target);// 更新最后开火时间tower.lastFired = currentTime;}// 寻找目标function findTarget(tower) {let closestEnemy = null;let minDistance = Infinity;for (const enemy of gameState.enemies) {const distance = Math.sqrt(Math.pow(tower.x - enemy.x, 2) + Math.pow(tower.y - enemy.y, 2));if (distance <= tower.range && distance < minDistance) {closestEnemy = enemy;minDistance = distance;}}return closestEnemy;}// 创建投射物function createProjectile(tower, target) {const projectile = {x: tower.x,y: tower.y,targetX: target.x,targetY: target.y,target: target,damage: tower.damage,speed: tower.projectileSpeed,color: tower.projectileColor,type: tower.type,splashRadius: tower.splashRadius || 0,chainTargets: tower.chainTargets || 0};gameState.projectiles.push(projectile);}// 更新投射物function updateProjectiles(deltaTime) {for (let i = gameState.projectiles.length - 1; i >= 0; i--) {const projectile = gameState.projectiles[i];// 检查目标是否仍然存在if (!gameState.enemies.includes(projectile.target)) {gameState.projectiles.splice(i, 1);continue;}// 计算方向const dx = projectile.targetX - projectile.x;const dy = projectile.targetY - projectile.y;const distance = Math.sqrt(dx * dx + dy * dy);// 标准化方向向量const dirX = dx / distance;const dirY = dy / distance;// 移动投射物projectile.x += dirX * projectile.speed * gameState.gameSpeed;projectile.y += dirY * projectile.speed * gameState.gameSpeed;// 检查是否击中目标const newDistance = Math.sqrt(Math.pow(projectile.targetX - projectile.x, 2) +Math.pow(projectile.targetY - projectile.y, 2));if (newDistance < 10) {// 处理击中handleProjectileHit(projectile);// 移除投射物gameState.projectiles.splice(i, 1);}}}// 处理投射物击中function handleProjectileHit(projectile) {// 创建爆炸效果createExplosion(projectile.targetX, projectile.targetY, projectile.color);// 根据投射物类型处理伤害if (projectile.type === 'explosive' && projectile.splashRadius > 0) {// 范围伤害for (const enemy of gameState.enemies) {const distance = Math.sqrt(Math.pow(enemy.x - projectile.targetX, 2) +Math.pow(enemy.y - projectile.targetY, 2));if (distance <= projectile.splashRadius) {damageEnemy(enemy, projectile.damage);}}} else if (projectile.type === 'electric' && projectile.chainTargets > 0) {// 链式伤害let currentTarget = projectile.target;let remainingChains = projectile.chainTargets;// 伤害初始目标damageEnemy(currentTarget, projectile.damage);// 寻找链式目标while (remainingChains > 0) {let nextTarget = null;let minDistance = Infinity;for (const enemy of gameState.enemies) {if (enemy === currentTarget || enemy.health <= 0) continue;const distance = Math.sqrt(Math.pow(enemy.x - currentTarget.x, 2) +Math.pow(enemy.y - currentTarget.y, 2));if (distance < 100 && distance < minDistance) { // 链击范围nextTarget = enemy;minDistance = distance;}}if (nextTarget) {// 创建链式闪电效果createLightning(currentTarget.x, currentTarget.y, nextTarget.x, nextTarget.y);// 伤害链式目标(伤害递减)const chainDamage = projectile.damage * (0.7 * remainingChains / projectile.chainTargets);damageEnemy(nextTarget, chainDamage);currentTarget = nextTarget;remainingChains--;} else {break;}}} else {// 普通伤害damageEnemy(projectile.target, projectile.damage);}}// 创建爆炸效果function createExplosion(x, y, color) {const explosion = {x: x,y: y,color: color || '#F44336',startTime: Date.now(),duration: 500 // 毫秒};gameState.explosions.push(explosion);}// 创建闪电效果function createLightning(x1, y1, x2, y2) {// 这个函数可以创建闪电效果的视觉元素// 为了简化,我们可以使用爆炸效果来模拟createExplosion((x1 + x2) / 2, (y1 + y2) / 2, '#FFEB3B');}// 伤害敌人function damageEnemy(enemy, damage) {enemy.health -= damage;// 检查敌人是否死亡if (enemy.health <= 0) {killEnemy(enemy);}}// 杀死敌人function killEnemy(enemy) {// 添加金币奖励gameState.gold += enemy.reward;// 更新统计gameState.enemiesKilled++;gameState.waveEnemies++;// 创建爆炸效果createExplosion(enemy.x, enemy.y);// 从敌人列表中移除const index = gameState.enemies.indexOf(enemy);if (index !== -1) {gameState.enemies.splice(index, 1);}// 更新UIupdateUI();// 检查波次是否结束checkWaveEnd();}// 更新敌人位置function updateEnemies(deltaTime) {for (let i = gameState.enemies.length - 1; i >= 0; i--) {const enemy = gameState.enemies[i];// 检查是否到达路径终点if (enemy.pathIndex >= pathPoints.length - 1) {// 敌人到达终点,减少生命值gameState.lives--;// 从敌人列表中移除gameState.enemies.splice(i, 1);// 更新UIupdateUI();// 检查游戏是否结束checkGameOver();continue;}// 获取下一个路径点const nextPoint = pathPoints[enemy.pathIndex + 1];// 计算方向const dx = nextPoint.x - enemy.x;const dy = nextPoint.y - enemy.y;const distance = Math.sqrt(dx * dx + dy * dy);// 如果接近下一个点,更新路径索引if (distance < 10) {enemy.pathIndex++;continue;}// 标准化方向向量const dirX = dx / distance;const dirY = dy / distance;// 移动敌人enemy.x += dirX * enemy.speed * gameState.gameSpeed;enemy.y += dirY * enemy.speed * gameState.gameSpeed;// 更新目标位置(用于投射物追踪)if (enemy.pathIndex + 1 < pathPoints.length) {const nextPathPoint = pathPoints[enemy.pathIndex + 1];enemy.targetX = nextPathPoint.x;enemy.targetY = nextPathPoint.y;}}}// 检查波次是否结束function checkWaveEnd() {if (gameState.waveEnemies >= gameState.waveEnemyLimit && gameState.enemies.length === 0) {// 波次结束gameState.isWaveActive = false;gameState.wave++;// 更新按钮状态startWaveBtn.disabled = false;startWaveBtn.classList.remove('opacity-50', 'cursor-not-allowed');// 显示通知showNotification(`第 ${gameState.wave - 1} 波完成! 准备第 ${gameState.wave} 波...`, 'success');// 更新UIupdateUI();}}// 检查游戏是否结束function checkGameOver() {if (gameState.lives <= 0) {endGame(false); // 失败} else if (gameState.wave > 20) {endGame(true); // 胜利}}// 结束游戏function endGame(isVictory) {gameState.gameOver = true;gameState.isPaused = true;// 停止游戏计时器stopGameTimer();// 显示游戏结束界面gameOverScreen.classList.remove('hidden');if (isVictory) {gameOverTitle.textContent = '胜利!';gameOverMessage.textContent = '你成功阻止了所有敌人的进攻!';} else {gameOverTitle.textContent = '游戏结束';gameOverMessage.textContent = '敌人突破了你的防线!';}// 更新最终统计finalWaveDisplay.textContent = gameState.wave;finalEnemiesKilledDisplay.textContent = gameState.enemiesKilled;finalTowersBuiltDisplay.textContent = gameState.towersBuilt;}// 暂停/继续游戏function togglePause() {if (gameState.gameOver) return;gameState.isPaused = !gameState.isPaused;if (gameState.isPaused) {pauseGameBtn.innerHTML = '<i class="fa fa-play mr-2"></i> 继续';pauseGameBtn.classList.remove('bg-info', 'hover:bg-blue-600');pauseGameBtn.classList.add('bg-success', 'hover:bg-green-600');// 停止游戏计时器stopGameTimer();} else {pauseGameBtn.innerHTML = '<i class="fa fa-pause mr-2"></i> 暂停';pauseGameBtn.classList.remove('bg-success', 'hover:bg-green-600');pauseGameBtn.classList.add('bg-info', 'hover:bg-blue-600');// 重启游戏计时器startGameTimer();}}// 重新开始游戏function restartGame() {// 重置游戏状态gameState = {gold: 500,lives: 20,wave: 1,gameSpeed: 1,isPaused: false,isWaveActive: false,selectedTowerType: null,towers: [],enemies: [],projectiles: [],explosions: [],weather: 'sunny',enemiesKilled: 0,towersBuilt: 0,gameTime: 0,gameTimeInterval: null,lastUpdateTime: 0,waveEnemies: 0,waveEnemiesSpawned: 0,waveEnemyLimit: 10,waveSpawnTimer: 0,waveSpawnInterval: 1000,gameOver: false};// 重置UIgameSpeedSlider.value = 1;speedValueDisplay.textContent = '1x';pauseGameBtn.innerHTML = '<i class="fa fa-pause mr-2"></i> 暂停';pauseGameBtn.classList.remove('bg-success', 'hover:bg-green-600');pauseGameBtn.classList.add('bg-info', 'hover:bg-blue-600');startWaveBtn.disabled = false;startWaveBtn.classList.remove('opacity-50', 'cursor-not-allowed');gameOverScreen.classList.add('hidden');// 清除塔选择towerButtons.forEach(btn => {btn.classList.remove('ring-2', 'ring-white');});// 更新UIupdateUI();// 重启游戏计时器startGameTimer();// 更新天气显示updateWeatherDisplay();showNotification('游戏已重置!', 'info');}// 更新游戏速度function updateGameSpeed() {gameState.gameSpeed = parseFloat(gameSpeedSlider.value);speedValueDisplay.textContent = gameState.gameSpeed + 'x';}// 开始游戏计时器function startGameTimer() {if (gameState.gameTimeInterval) return;gameState.gameTimeInterval = setInterval(() => {if (!gameState.isPaused && !gameState.gameOver) {gameState.gameTime++;updateGameTimeDisplay();}}, 1000);}// 停止游戏计时器function stopGameTimer() {if (gameState.gameTimeInterval) {clearInterval(gameState.gameTimeInterval);gameState.gameTimeInterval = null;}}// 更新游戏时间显示function updateGameTimeDisplay() {const minutes = Math.floor(gameState.gameTime / 60);const seconds = gameState.gameTime % 60;gameTimeDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;}// 显示波次通知function showWaveNotification(message) {const notification = document.createElement('div');notification.className = 'wave-notification';notification.textContent = message;document.body.appendChild(notification);// 2秒后移除setTimeout(() => {notification.remove();}, 2000);}// 显示通知function showNotification(message, type = 'info') {const notification = document.createElement('div');notification.className = 'fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 transition-all transform translate-x-full opacity-0';// 设置颜色switch (type) {case 'success':notification.classList.add('bg-green-500');break;case 'error':notification.classList.add('bg-red-500');break;case 'warning':notification.classList.add('bg-yellow-500');break;default:notification.classList.add('bg-blue-500');}notification.textContent = message;document.body.appendChild(notification);// 显示动画setTimeout(() => {notification.classList.remove('translate-x-full', 'opacity-0');}, 10);// 3秒后隐藏setTimeout(() => {notification.classList.add('translate-x-full', 'opacity-0');// 移除元素setTimeout(() => {notification.remove();}, 300);}, 3000);}// 更新UIfunction updateUI() {goldDisplay.textContent = gameState.gold;livesDisplay.textContent = gameState.lives;waveDisplay.textContent = gameState.wave;enemiesKilledDisplay.textContent = gameState.enemiesKilled;towersBuiltDisplay.textContent = gameState.towersBuilt;}// 绘制游戏function drawGame() {// 清除画布ctx.clearRect(0, 0, canvas.width, canvas.height);// 绘制网格drawGrid();// 绘制路径drawPath();// 绘制塔drawTowers();// 绘制敌人drawEnemies();// 绘制投射物drawProjectiles();// 绘制爆炸效果drawExplosions();// 绘制塔范围指示器(如果有选中的塔类型)if (gameState.selectedTowerType) {drawRangeIndicator();}}// 绘制网格function drawGrid() {ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';ctx.lineWidth = 1;// 绘制垂直线for (let x = 0; x <= canvas.width; x += GRID_SIZE) {ctx.beginPath();ctx.moveTo(x, 0);ctx.lineTo(x, canvas.height);ctx.stroke();}// 绘制水平线for (let y = 0; y <= canvas.height; y += GRID_SIZE) {ctx.beginPath();ctx.moveTo(0, y);ctx.lineTo(canvas.width, y);ctx.stroke();}}// 绘制路径function drawPath() {ctx.strokeStyle = PATH_COLOR;ctx.lineWidth = 40;ctx.lineCap = 'round';ctx.lineJoin = 'round';ctx.beginPath();ctx.moveTo(pathPoints[0].x, pathPoints[0].y);for (let i = 1; i < pathPoints.length; i++) {ctx.lineTo(pathPoints[i].x, pathPoints[i].y);}ctx.stroke();// 绘制路径点ctx.fillStyle = '#7f8c8d';for (const point of pathPoints) {ctx.beginPath();ctx.arc(point.x, point.y, 5, 0, Math.PI * 2);ctx.fill();}}// 绘制塔function drawTowers() {for (const tower of gameState.towers) {// 绘制塔基ctx.fillStyle = tower.color;ctx.beginPath();ctx.arc(tower.x, tower.y, 20, 0, Math.PI * 2);ctx.fill();// 绘制塔图标ctx.fillStyle = 'white';ctx.font = '16px Arial';ctx.textAlign = 'center';ctx.textBaseline = 'middle';let icon = '⚡';if (tower.type === 'basic') icon = '🔴';else if (tower.type === 'explosive') icon = '💣';ctx.fillText(icon, tower.x, tower.y);// 绘制攻击范围(可选)// ctx.strokeStyle = 'rgba(255, 255, 255, 0.2)';// ctx.beginPath();// ctx.arc(tower.x, tower.y, tower.range, 0, Math.PI * 2);// ctx.stroke();}}// 绘制敌人function drawEnemies() {for (const enemy of gameState.enemies) {// 绘制生命值条const healthPercent = enemy.health / enemy.maxHealth;const barWidth = enemy.size * 2;const barHeight = 4;ctx.fillStyle = '#e74c3c';ctx.fillRect(enemy.x - barWidth / 2, enemy.y - enemy.size - 10, barWidth, barHeight);ctx.fillStyle = '#2ecc71';ctx.fillRect(enemy.x - barWidth / 2, enemy.y - enemy.size - 10, barWidth * healthPercent, barHeight);// 绘制敌人ctx.fillStyle = enemy.color;ctx.beginPath();ctx.arc(enemy.x, enemy.y, enemy.size, 0, Math.PI * 2);ctx.fill();// 绘制敌人边框ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';ctx.lineWidth = 2;ctx.stroke();}}// 绘制投射物function drawProjectiles() {for (const projectile of gameState.projectiles) {ctx.fillStyle = projectile.color;ctx.beginPath();ctx.arc(projectile.x, projectile.y, 4, 0, Math.PI * 2);ctx.fill();}}// 绘制爆炸效果function drawExplosions() {const currentTime = Date.now();for (let i = gameState.explosions.length - 1; i >= 0; i--) {const explosion = gameState.explosions[i];const elapsed = currentTime - explosion.startTime;const progress = elapsed / explosion.duration;if (progress >= 1) {// 爆炸效果结束,移除gameState.explosions.splice(i, 1);continue;}// 绘制爆炸const radius = 50 * progress;const alpha = 1 - progress;ctx.fillStyle = `rgba(255, 255, 255, ${alpha * 0.5})`;ctx.beginPath();ctx.arc(explosion.x, explosion.y, radius, 0, Math.PI * 2);ctx.fill();ctx.strokeStyle = `rgba(255, 193, 7, ${alpha})`;ctx.lineWidth = 3;ctx.beginPath();ctx.arc(explosion.x, explosion.y, radius * 0.7, 0, Math.PI * 2);ctx.stroke();}}// 绘制范围指示器function drawRangeIndicator() {// 获取鼠标位置const rect = canvas.getBoundingClientRect();const mouseX = (mousePos.x - rect.left) * (canvas.width / rect.width);const mouseY = (mousePos.y - rect.top) * (canvas.height / rect.height);const towerConfig = towerTypes[gameState.selectedTowerType];// 检查位置是否有效const isValid = isValidTowerPosition(mouseX, mouseY);// 绘制范围指示器ctx.strokeStyle = isValid ? 'rgba(46, 204, 113, 0.5)' : 'rgba(231, 76, 60, 0.5)';ctx.lineWidth = 2;ctx.beginPath();ctx.arc(mouseX, mouseY, towerConfig.range, 0, Math.PI * 2);ctx.stroke();// 绘制塔预览ctx.fillStyle = isValid ? towerConfig.color : 'rgba(231, 76, 60, 0.7)';ctx.beginPath();ctx.arc(mouseX, mouseY, 20, 0, Math.PI * 2);ctx.fill();// 绘制塔图标ctx.fillStyle = 'white';ctx.font = '16px Arial';ctx.textAlign = 'center';ctx.textBaseline = 'middle';let icon = '⚡';if (gameState.selectedTowerType === 'basic') icon = '🔴';else if (gameState.selectedTowerType === 'explosive') icon = '💣';ctx.fillText(icon, mouseX, mouseY);}// 跟踪鼠标位置const mousePos = { x: 0, y: 0 };canvas.addEventListener('mousemove', (event) => {mousePos.x = event.clientX;mousePos.y = event.clientY;});// 游戏主循环function gameLoop(timestamp) {if (!gameState.lastUpdateTime) {gameState.lastUpdateTime = timestamp;}const deltaTime = timestamp - gameState.lastUpdateTime;gameState.lastUpdateTime = timestamp;if (!gameState.isPaused && !gameState.gameOver) {// 更新游戏状态updateGame(deltaTime);}// 绘制游戏drawGame();// 继续游戏循环requestAnimationFrame(gameLoop);}// 更新游戏状态function updateGame(deltaTime) {// 更新波次生成if (gameState.isWaveActive) {gameState.waveSpawnTimer += deltaTime;if (gameState.waveSpawnTimer >= gameState.waveSpawnInterval) {spawnEnemy();gameState.waveSpawnTimer = 0;}}// 更新塔攻击const currentTime = Date.now();for (const tower of gameState.towers) {towerAttack(tower, currentTime);}// 更新投射物updateProjectiles(deltaTime);// 更新敌人updateEnemies(deltaTime);}// 初始化游戏window.onload = initGame;</script></body></html>```