File indexing completed on 2024-04-28 07:51:24

0001 /***************************************************************************
0002 *   KBlocks, a falling blocks game by KDE                                *
0003 *   SPDX-FileCopyrightText: 2010 Zhongjie Cai <squall.leonhart.cai@gmail.com>       *
0004 *                                                                         *
0005 *   SPDX-License-Identifier: GPL-2.0-or-later
0006 ***************************************************************************/
0007 #include "KBlocksGameRecorder.h"
0008 #include "utils.h"
0009 
0010 KBlocksGameRecorder::KBlocksGameRecorder()
0011 {
0012     mGameRecord.clear();
0013 }
0014 
0015 KBlocksGameRecorder::~KBlocksGameRecorder()
0016 {
0017     mGameRecord.clear();
0018 }
0019 
0020 void KBlocksGameRecorder::append(int index, int type, int value)
0021 {
0022     _game_record_data tmpLastData;
0023     tmpLastData.index = index;
0024     tmpLastData.type = type;
0025     tmpLastData.value = value;
0026     tmpLastData.time = Utils::getMillisecOfNow();
0027     mGameRecord.push_back(tmpLastData);
0028 }
0029 
0030 void KBlocksGameRecorder::save(const char *fileName, bool isBinaryMode)
0031 {
0032     FILE *pFile = fopen(fileName, "w");
0033     if (isBinaryMode) {
0034         saveBinary(pFile);
0035     } else {
0036         saveText(pFile);
0037     }
0038     fclose(pFile);
0039 }
0040 
0041 void KBlocksGameRecorder::saveText(FILE *pFile)
0042 {
0043     int tmpTime = 0;
0044     timeLong oldTime = mGameRecord.front().time;
0045     list<_game_record_data>::iterator it;
0046     for (it = mGameRecord.begin(); it != mGameRecord.end(); ++it) {
0047         tmpTime = (int)(it->time - oldTime);
0048         oldTime = it->time;
0049         fprintf(pFile, "%d %s %d %d\n", tmpTime, KBlocksRecordText[it->type], it->index, it->value);
0050     }
0051 }
0052 
0053 void KBlocksGameRecorder::saveBinary(FILE *pFile)
0054 {
0055     int tmpTime = 0;
0056     timeLong oldTime = mGameRecord.front().time;
0057     list<_game_record_data>::iterator it;
0058     for (it = mGameRecord.begin(); it != mGameRecord.end(); ++it) {
0059         tmpTime = (int)(it->time - oldTime);
0060         oldTime = it->time;
0061         if (tmpTime > 255) {
0062             while (tmpTime > 255) {
0063                 writeByte(pFile, 255);
0064                 writeByte(pFile, RecordDataType_Skipped);
0065                 writeByte(pFile, it->index);
0066                 writeByte(pFile, it->value);
0067                 tmpTime -= 255;
0068             }
0069         }
0070         writeByte(pFile, tmpTime);
0071         writeByte(pFile, it->type);
0072         writeByte(pFile, it->index);
0073         writeByte(pFile, it->value);
0074     }
0075 }
0076 
0077 void KBlocksGameRecorder::writeByte(FILE *pFile, int value)
0078 {
0079     int tmpByte = (value & 0xFF);
0080     fputc(tmpByte, pFile);
0081 }
0082