近來達芬奇密碼熱抄,也從網上找來看了,對中文官網首頁的游戲產生了愛好.由于是小時候看過這個數學題,現在忽然看到備感親切.所以用SQL模擬了一個.(中文官方網站見http://davincicode.leiling.com/)
create PRoc davinci (@intarray varchar(1000))as--******************--2004.7--******************declare @sp varchar(1)set @sp=','
declare @i int,@j int,@maxq int
--初始化if charindex(@sp,@intarray)=0begin if object_id('tempdb..##t') is not null drop table ##t
if isnumeric(@intarray)=0 begin print '輸入參數必須是數字。' return end create table ##t(id int identity(1,1),q int) set @i=floor(10+rand()*30) insert into ##t(q) values(@i) print '目標:'+cast(@i as varchar(2))end
--輪回游戲elsebegin
--判定游戲是否結束 if object_id('tempdb..##t') is null begin print '本回合已經結束,大俠請重新來過!' return end
--驗證用戶輸入數合法性 if isnumeric(right(@intarray,charindex(@sp,reverse(@intarray))-1))=0 begin print '輸入參數必須是數字。' return end set @i=cast(right(@intarray,charindex(@sp,reverse(@intarray))-1) as int) set @maxq=(select max(q) from ##t where id>1) if @i<=isnull(@maxq,0) begin print '輸入參數必須大于當前最大數。' return end if @i-isnull(@maxq,1)>3 begin print '輸入參數超過范圍。' return end if @i>(select q from ##t where id=1) begin print '輸入參數不得大于目標數。' return end
--插入用戶輸入數 insert into ##t(q) values(@i) print '你輸入:'+cast(@i as varchar(2)) --判定勝敗 if @i=(select q from ##t where id=1) begin drop table ##t ----------------------------------' print '勝敗乃兵家常事,大俠請重新來過!' return end if @i=(select q from ##t where id=1)-1 begin drop table ##t print '達芬奇:'+cast(@i+1 as varchar(2)) print '-----------------' print '恭喜!你獲勝了。' return end
--插入達芬奇應答數 if (select q-1 from ##t where id=1)%4=0 set @j=(select count(id) from ##t where id%2=1)*4 else begin set @j=(select q-1 from ##t where id=1)%4+((select count(id) from ##t where id%2=1)-1)*4 if @j<(select max(q) from ##t where id>1) set @j=@j+4 end if @i=@j set @j=@j+floor(1+rand()*3) insert into ##t values(@j) print '達芬奇:'+cast(@j as varchar(2))end
--完整版顯示select 目標數=q,你輸入=null,達芬奇=null,下次輸入='1,2,3' from ##t where id=1union allselect 目標數=null,你輸入,達芬奇 ,下次輸入=case when charindex(','+目標數+',',','+下次輸入+',')=0 then 下次輸入 else left(left(下次輸入,charindex(','+目標數+',',','+下次輸入+',')+len(目標數)), len(left(下次輸入,charindex(','+目標數+',',','+下次輸入+',')+len(目標數)))- charindex(',',reverse(left(下次輸入,charindex(','+目標數+',',','+下次輸入+',')+len(目標數))))) endfrom (select 目標數,你輸入,達芬奇 ,下次輸入=cast(達芬奇+1 as varchar(2))+',' +cast(達芬奇+2 as varchar(2))+',' +cast(達芬奇+3 as varchar(2))from (select 目標數=cast((select q from ##t where id=1) as varchar(2)) ,你輸入=max(case when id%2=0 then q else 0 end) ,達芬奇=max(case when id%2=1 then q else 0 end)from ##twhere id>1group by floor(id/2)) a) b
/*--簡化版顯示select case when id=1 then '目標數:' when id%2=0 then '你輸入:' when id%2=1 and id>1 then '達芬奇:' end ,qfrom ##t*/
游戲規則:系統隨機產生目標數,雙方從數字1開始輪回應答,數字必須連續,每回合最多可以選擇3個數字,先到目標數者為負。
游戲說明:執行 exec davinci '2' 開始程序,其中數字2可以為任意數字,系統產生隨機目標數。你開始應答,應答數以逗號『,』分隔,如:exec davinci '2,1',然后系統自動回應答,如4。接著開始下一輪應答:exec davinci '2,1,6' ………