การทำส่วน High Score ของเกม
2010-05-04 Games 2,700การสร้างส่วน High Score นั้นมีวิธีการ Code หลายแบบ Code Tutorial นี้เป็นเพียงตัวอย่างหนึ่งเพื่อให้เข้าใจหลักการเท่านั้นครับ
1. ขั้นแรกการประกาศตัวแปรที่จะเก็บ High Score และ Player Score
type Highscore
Name as string
Score as integer
endtype
rem จำนวน highscore ที่ต้องการเก็บ
MaxHighscore=10
rem สร้างอาเรย์เก็บข้อมูล highscore
Dim HighScore(MaxHighscore) as Highscore
rem ตัวแปรเก็บคะแนนของ Player
Dim Player(1) as Highscore
2. ส่วนการใส่ชื่อ และ score เพื่อทำการทดสอบ
rem ส่วนทดสอบลองการใส่คะแนน player
input "Enter your name : ",Player(1).Name
input "Enter your score(0-1000) : ",Player(1).Score
WHILE Player(1).Score<0 and Player(1).Score>1000
print "Your score must between 0-1000"
input "Enter your score again (0-1000) : ",Player(1).Score
ENDWHILE
cls
3. ส่วนการเช็คไฟล์ score และอ่านค่า score เดิม
rem เช็คไฟล์ score และอ่านค่า high score อันเดิม
if file Exist("score.dat")
open to read 1,"score.dat"
for i=1 to MaxHighscore
read string 1,HighScore(i).Name
read string 1,BuffStr$
HighScore(i).Score=Val(BuffStr$)
Next i
Close file 1
Endif
4. ส่วนการแทรกคะแนนและเรียงลำดับ high Score
rem BuffInsert ไว้เช็คลำดับที่จะทำการแทรกคะแนนใหม่
BuffInsert=1
for i=1 to MaxHighscore
if HighScore(i).Score>=Player(1).Score
rem เมื่อคะแนนของผู้เล่นน้อยกว่าให้เก็บค่าการแทรกไว้เป็นลำดับถัดไป
BuffInsert=i+1
endif
next i
rem ย้ายลำดับของ high score ลงโดยดูตำแหน่งที่ย้ายจากค่า BuffInsert
for i=MaxHighscore-1 to BuffInsert step -1
HighScore(i+1).Score=HighScore(i).Score
HighScore(i+1).Name=HighScore(i).Name
rem ส่วนทดสอบไว้ดูค่า i และ buffinsert
rem print "i=",i," | BuffInsert=",BuffInsert
next i
rem แทรกคะแนน player เมื่อคะแนนอยู่ในลำดับของ highscore
if BuffInsert<=MaxHighscore
HighScore(BuffInsert).Score=Player(1).Score
HighScore(BuffInsert).Name=Player(1).NAME
endif
5. ส่้วนการเขียนไฟล์ score ใหม่
if file Exist("score.dat")
delete File "score.dat"
open to Write 1,"score.dat"
for i=1 to MaxHighscore
Write string 1,HighScore(i).Name
Write string 1,Str$(HighScore(i).Score)
Next i
Close file 1
Endif
6. ส่วนโชว์คะแนน High Score
for i=1 to MaxHighscore
print "Name : ",HighScore(i).Name," Score : ",HighScore(i).Score
next i
wait key
end
High Score Sample.exe & Code [ Download ]
highscore code | Darkbasic Tutorials