參考 JSP 版拼圖邏輯移植而成的 ASP 3x3 滑塊拼圖,利用 Session 保存遊戲狀態,透過 QueryString 參數切換「開始/顯示/移動」三大功能。適合初學者理解 ASP 狀態管理與陣列操作。
action=start:初始化 3x3 陣列(0-8),打亂順序,存入 Session,導向顯示頁action=see:從 Session 讀取陣列,輸出 HTML 表格,數字格產生連結帶 h,l,action=move 參數action=move:依傳入座標檢查上下左右是否為空格(0),若相鄰則交換位置,更新 Session,導回顯示頁<%@ Language=VBScript CodePage=950 %>
<html><head><title>ASP 拼圖遊戲</title></head><body>
<div align="center"><h1>排字遊戲 (3x3 拼圖)</h1></div>
<a href="pinzi.asp?action=start">開始新遊戲</a> <hr/>
<%
action = Request.QueryString("action")
If action = "" Or action = "start" Then Call StartGame()
If action = "see" Then Call ShowBoard()
If action = "move" Then Call MoveTile()
%>
<%
' ===== 初始化並打亂 =====
Sub StartGame()
Dim grid(2,2), num, i, h1, l1, h2, l2, tmp
num = 0
Randomize
For i = 0 To 2
For l = 0 To 2
grid(i,l) = num
num = num + 1
Next
Next
' 亂數交換 10 次
For i = 1 To 10
h1 = Int(3 * Rnd) : l1 = Int(3 * Rnd)
h2 = Int(3 * Rnd) : l2 = Int(3 * Rnd)
tmp = grid(h1,l1) : grid(h1,l1) = grid(h2,l2) : grid(h2,l2) = tmp
Next
Session("grid") = grid
Response.Redirect "pinzi.asp?action=see"
End Sub
' ===== 顯示棋盤 =====
Sub ShowBoard()
Dim grid, h, l
grid = Session("grid")
If IsEmpty(grid) Then Response.Redirect "pinzi.asp?action=start" : Exit Sub
%>
<table width="300" align="center" border="1" height="300" style="border-collapse:collapse">
<%
For h = 0 To 2
Response.Write ""
For l = 0 To 2
Response.Write ""
If grid(h,l) <> 0 Then
Response.Write "" & grid(h,l) & ""
Else
Response.Write " "
End If
Response.Write " "
Next
Response.Write " "
Next
%>
</table>
<% End Sub %>
<%
' ===== 移動邏輯 =====
Sub MoveTile()
Dim grid, h, l
grid = Session("grid")
h = CInt(Request.QueryString("h"))
l = CInt(Request.QueryString("l"))
' 檢查四個方向是否為 0 (空格),若是則交換
If h > 0 And grid(h-1,l) = 0 Then grid(h-1,l)=grid(h,l) : grid(h,l)=0
If h < 2 And grid(h+1,l) = 0 Then grid(h+1,l)=grid(h,l) : grid(h,l)=0
If l > 0 And grid(h,l-1) = 0 Then grid(h,l-1)=grid(h,l) : grid(h,l)=0
If l < 2 And grid(h,l+1) = 0 Then grid(h,l+1)=grid(h,l) : grid(h,l)=0
Session("grid") = grid
Response.Redirect "pinzi.asp?action=see"
End Sub
%>
<hr><div align="center">© 2005-2008 <a href="https://www.DeepTeach.com">深度開發</a></div>
</body></html>
Session("grid") 將二維陣列跨請求保存。Randomize 僅需呼叫一次初始化亂數種子,後續 Rnd 產生 0~1 浮點數,配合 Int(3*Rnd) 取 0-2 整數。Response.Redirect 回顯示頁,防止重新整理重複執行 Move。Session("steps")) 與計時器這個小遊戲雖簡單,卻涵蓋 ASP 核心技術:Session 狀態管理、陣列操作、QueryString 參數解析、條件判斷、HTML 動態產生、Redirect 模式。是從「Hello World」邁向互動式 Web 應用的優秀練習題。