[問題] 遊戲計時器

看板C_and_CPP作者 (魯魯魯魯魯魯)時間10年前 (2015/01/07 09:35), 編輯推噓2(2012)
留言14則, 5人參與, 最新討論串3/3 (看更多)
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) DEV C++ 問題(Question): 用C寫了一個小遊戲 需要在加入倒數計時器才完成 但是發現只要倒數計時器運作 遊戲就沒辦法動 雖然GOOGLE到執行緒 但是小弟是初學者短時間內還沒辦法參透 附上程式碼希望板上各位高手給個提示和概念讓我知道哪裡錯了 程式碼(Code):(請善用置底文網頁, 記得排版) #include <stdio.h> #include <stdlib.h> #include <graphics.h> #include <conio.h> #include <time.h> #include <windows.h> int main(void) { -------------------- | | | //遊戲程式宣告// | | | -------------------- initwindow(700,700); unsigned int x_hours=0; unsigned int x_minutes=0; unsigned int x_seconds=0; unsigned int x_milliseconds=0; unsigned int totaltime=0,count_down_time_in_secs=0,time_left=0; clock_t x_startTime,x_countTime; count_down_time_in_secs=10; x_startTime=clock(); time_left=count_down_time_in_secs-x_seconds; while(time_left>0) { x_countTime=clock(); x_milliseconds=x_countTime-x_startTime; x_seconds=(x_milliseconds/(CLOCKS_PER_SEC))-(x_minutes*60); x_minutes=(x_milliseconds/(CLOCKS_PER_SEC))/60; x_hours=x_minutes/60; time_left=count_down_time_in_secs-x_seconds; } return 0; do { ---------------- | | |// 遊戲程式// | | | ---------------- } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.127.29.173 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1420623300.A.536.html

01/07 19:29, , 1F
這程式就陷到while loop 裡,不執行下面的do loop 了
01/07 19:29, 1F

01/07 19:29, , 2F
所以需要兩個執行緒,一個跑遊戲程式一個跑計時器
01/07 19:29, 2F

01/07 19:30, , 3F
你要簡單一點可以把這兩個loop 寫在一起=w=
01/07 19:30, 3F

01/07 22:02, , 4F
thread 然後把計時的funtion 丟給他執行 就可以了
01/07 22:02, 4F

01/08 00:41, , 5F
遊戲程式在 return 0; 後面?這樣怎麼跑?
01/08 00:41, 5F

01/08 00:44, , 6F
另外,一定要用多執行緒,搞不懂就別寫了。
01/08 00:44, 6F

01/08 01:52, , 7F
其實是可以single thread的
01/08 01:52, 7F

01/08 01:52, , 8F
#1KcwFJFn 不過你設計整個要改就是
01/08 01:52, 8F

01/08 01:53, , 9F
那篇後面提到的timerfd都算是multi-thread 看前面就好
01/08 01:53, 9F

01/08 11:06, , 10F
先把主流程改成update loop的形式 (參考Killercat)
01/08 11:06, 10F

01/08 11:06, , 11F
然後看你要用state machine或coroutine都很好
01/08 11:06, 11F

01/08 11:07, , 12F
這地方不該用thread,遊戲中要計時的物件很多
01/08 11:07, 12F

01/08 11:08, , 13F
如果每個都用thread,race condition會搞死你
01/08 11:08, 13F

01/08 15:57, , 14F
原來如此,受教了。
01/08 15:57, 14F
文章代碼(AID): #1KhFt4Ks (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1KhFt4Ks (C_and_CPP)