[C++] 270 SDL : テトリス画面収録 その2 psコマンド プロセスID

[M1 Mac, Monterey 12.6.3, clang 13.0.0, SDL 2.26.2, ChatGPT Plus, NO IDE]

CPUの別コアで並列実行した画面収録をゲームオーバー時に自動で終わらせるようにしました。前回発生したx座標のズレは修正済です。

psコマンドでFFmpeg関連のプロセスIDを取得し、順次killコマンドで停止するという内容です。

ただappファイルについては収録開始時に環境設定のセキュリティで画面収録を都度許可する必要がありプレイに支障があります。おそらくApple公証を通せば許可不要になると思います。実行ファイルは問題ありません。

ChatGPTを使うようになってから、プログラミングに関する調査でGoogleを使う頻度が激減しました。ただ一見考えているようで何も考えていないので、自身のコード検証力が問われるところです。

// 文字列分割(psコマンドにおける出力を処理)
vector<string> splitString(string s, string delimiter) {
    vector<string> tokens;
    size_t delimiterPos = s.find(delimiter);
    while (delimiterPos != string::npos) {
        string token = s.substr(0, delimiterPos);
        tokens.push_back(token);
        s.erase(0, delimiterPos + delimiter.length());
        delimiterPos = s.find(delimiter);
    }
    tokens.push_back(s);
    return tokens;
}

// プロセスID取得
vector<string> getProcessID(){
	FILE* pipe = popen("ps -ef | grep ffmpeg", "r");
    if (!pipe) return {};
	
    char buffer[512];
    string output = "";
    while (!feof(pipe)) {
        if (fgets(buffer, 128, pipe) != NULL)
            output += buffer;
    }
    pclose(pipe);

	cout << "output: " << output << endl;
	string userID = output.substr(2, 3);
	cout << "userID: " << userID << endl;

	vector<string> tokens = splitString(output, userID);
	vector<string> processIDs;
	for (int i = 0; i < tokens.size(); i++){
		cout << "token: " << tokens[i] << endl;
		string id = tokens[i].substr(1, 5);
		processIDs.push_back(id);
		cout << "id: " << id << endl;
	}

    return processIDs;
}

// プロセスID停止
void stopProcess(){
	vector<string> ids = getProcessID();

	for (string id: ids){
		string cmd = "kill " + id;

		if(!system(cmd.c_str())){
			cout << "id不適合" << endl;
		};
	}
}

[C++] 269 SDL : テトリス画面収録 その1 FFmpegを並列実行

[M1 Mac, Monterey 12.6.3, clang 13.0.0, SDL 2.26.2, ChatGPT Plus, NO IDE]

テトリスのプレイ画面収録機能を実装中です。

ffmpegコマンドをCPUの別コアで並列実行します。コマンドの末尾に&を付けると別コアでの実行になります。そうしないと録画が終わるまでゲーム開始が保留状態です。

録画開始はスムーズですが、録画停止についてはプロセスIDを終了させる必要があります。これからコードを書いていきます。

画面のx座標がなぜかズレているため要調整です。

ズレて収録されたプレイ動画
void App::Run()
{
	Uint32 lastTimeMs = SDL_GetTicks();
	auto lastTime = std::chrono::high_resolution_clock::now();

	bool bDone = false;
	while(!bDone )
	{
		GameInput gameInput = {};
		SDL_JoystickUpdate();

		// respond to events
		SDL_Event event;
		while( SDL_PollEvent( &event ) )
		{
			if(event.type == SDL_QUIT)
			{
				bDone = true;
			}

			// 落下速度ボタン選択
			if(event.type == SDL_MOUSEBUTTONDOWN)
			{
				mouseX = event.motion.x;
				mouseY = event.motion.y;
				SDL_Delay(10);
				selectButton(slowButton, normalButton, fastButton, mouseX, mouseY);
			}

			if(event.type == SDL_JOYBUTTONDOWN)
			{
				switch (event.jbutton.button){
					case 2:{	// □ボタン:スタート
						gameInput.bStart = true;
						start = std::chrono::steady_clock::now();
						scores = {};
						dates = {};
						fullDates = {};
						numAllScores = {};
						rank = 0;
						DrawPlayingCount = 0;
						GeneratorCount = 0;
						arr = {};
						modeDetect();

						// 画面収録開始						
						string cmd = "/opt/homebrew/bin/ffmpeg -f avfoundation -framerate 30 -video_size 1280x720 -i \"Capture screen 0\" -vf \"crop=1280:720:400:150\" -vcodec libx264 -pix_fmt yuv420p -r 30 -preset ultrafast -tune zerolatency -crf 28 -x264-params \"nal-hrd=cbr:force-cfr=1\" -maxrate 3M -bufsize 6M /Users/[ユーザID]/TetrisDX/video/test.mp4 &";
						system(cmd.c_str());

						break;
					}
					case 13:{	// 左ボタン
						gameInput.bMoveLeft = true;
						break;
					}
					case 14:{	// 右ボタン
						gameInput.bMoveRight = true;
						break;
					}
					case 1:{	// ○ボタン:反時計回り回転
						gameInput.bRotateClockwise = true;
						break;
					}
					case 0:{	// ×ボタン:時計回り回転
						gameInput.bRotateAnticlockwise = true;
						break;
					}
					case 12:{	// 下ボタン:一気に落下
						gameInput.bHardDrop = true;
						break;
					}
					case 11:{	// 上ボタン:徐々に落下
						gameInput.bSoftDrop = true;
						break;
					}
					case 10:{	// R1ボタン:落下速度ボタン選択
						buttonCount++;
						if (buttonCount % 3 == 1){
							fastButton.selected = true;
							normalButton.selected = false;
							s_initialFramesPerFallStep = 24;

						} else if (buttonCount % 3 == 2){
							slowButton.selected = true;
							fastButton.selected = false;
							s_initialFramesPerFallStep = 48;

						} else {
							normalButton.selected = true;
							slowButton.selected = false;
							s_initialFramesPerFallStep = 32;
						}
						break;
					}
					case 9:{	// L1ボタン:スタート画面
						m_gameState = kGameState_TitleScreen;
						break;
					}
					case 6:{	// optionsボタン:ゲーム終了
						// cout << "ゲーム終了" << endl;
						bDone = true;
						break;
					}
					default:{
						// cout << "default" << endl;
						break;
					}
				}
			}
		}

		Uint32 currentTimeMs = SDL_GetTicks();
		Uint32 deltaTimeMs = currentTimeMs - lastTimeMs;
		lastTimeMs = currentTimeMs;
		HP_UNUSED( deltaTimeMs );
		
		auto currentTime = std::chrono::high_resolution_clock::now();
		auto deltaTime = currentTime - lastTime;
		std::chrono::microseconds deltaTimeMicroseconds = std::chrono::duration_cast<std::chrono::microseconds>(deltaTime);
		float deltaTimeSeconds = 0.000001f * (float)deltaTimeMicroseconds.count();
		lastTime = currentTime;

		mGame->Update(gameInput, deltaTimeSeconds );

		mRenderer->Clear();
		mGame->Draw( *mRenderer );
		mRenderer->Present();
	}
}

[C++] 268 実行ファイルからappファイルを作成 シェルスクリプトをバイナリ化 引数2つ

[M1 Mac, Monterey 12.6.3, clang 13.0.0, SDL 2.26.2, ChatGPT Plus, NO IDE]

Makefileのアプリファイル作成するところを1行減らすためにmakeAppコマンドの引数を2つに増やしました。

実行ファイル作成とappファイル作成がそれぞれ1行にまとまり、すっきりしました。

# 実行ファイル
TARGETDIR = ./bin
TARGET = TetrisDX

# oファイルから実行ファイル・appファイル作成
$(TARGET):$(OBJS)
	$(COMPILER) -o $(TARGETDIR)/$@ $(OBJS) $(LIBRARY0) $(LIBRARY) $(LDFLAGS)
	./sh/makeApp $(TARGETDIR) $(TARGET)
#!/bin/sh

cp $1/$2 $2
mkdir $2.app
mkdir $2.app/Contents
mkdir $2.app/Contents/MacOS
mv $2 $2.app/Contents/MacOS
mkdir $2.app/Contents/Resources
cp ./images/$2.icns $2.app/Contents/Resources
plutil -create xml1 $2.app/Contents/Info.plist
plutil -insert 'CFBundleInfoDictionaryVersion' -string "6.0" $2.app/Contents/Info.plist
plutil -insert 'CFBundleExecutable' -string $2 $2.app/Contents/Info.plist
plutil -insert 'CFBundleIdentifier' -string "" $2.app/Contents/Info.plist
plutil -insert 'CFBundleName' -string $2 $2.app/Contents/Info.plist
plutil -insert 'CFBundlePackageType' -string "APPL" $2.app/Contents/Info.plist
plutil -insert 'CFBundleIconFile' -string $2.icns $2.app/Contents/Info.plist
plutil -insert 'NSHighResolutionCapable' -bool true $2.app/Contents/Info.plist

[C++] 267 実行ファイルからappファイルを作成 シェルスクリプトをバイナリ化

[M1 Mac, Monterey 12.6.3, clang 13.0.0, SDL 2.26.2, ChatGPT Plus, NO IDE]

前回の続きです。

シェルスクリプトの内容を見られたくない場合はshcコマンドでバイナリ化します。

shcコマンドはshファイルをC言語に変換しコンパイルしてくれます。C言語のコードも同時に生成しますので、内容を解析するのも一興です。

chmodコマンドによるアクセス権限付与はいらなくなります。

# shcをインストール
homebrew install shc

# shファイルをバイナリ化(.xが末尾に付く)
shc -f shファイル
# 実行ファイル
TARGETDIR = ./bin
TARGET = TetrisDX

# oファイルから実行ファイル作成(makeApp.sh.xはmakeAppにリネーム)
$(TARGET):$(OBJS)
	$(COMPILER) -o $(TARGETDIR)/$@ $(OBJS) $(LIBRARY0) $(LIBRARY) $(LDFLAGS)
	cp $(TARGETDIR)/$(TARGET) $(TARGET)
	./sh/makeApp $(TARGET)
#!/bin/sh

mkdir $1.app
mkdir $1.app/Contents
mkdir $1.app/Contents/MacOS
mv $1 $1.app/Contents/MacOS
mkdir $1.app/Contents/Resources
cp ./images/$1.icns $1.app/Contents/Resources
plutil -create xml1 $1.app/Contents/Info.plist
plutil -insert 'CFBundleInfoDictionaryVersion' -string "6.0" $1.app/Contents/Info.plist
plutil -insert 'CFBundleExecutable' -string $1 $1.app/Contents/Info.plist
plutil -insert 'CFBundleIdentifier' -string "" $1.app/Contents/Info.plist
plutil -insert 'CFBundleName' -string $1 $1.app/Contents/Info.plist
plutil -insert 'CFBundlePackageType' -string "APPL" $1.app/Contents/Info.plist
plutil -insert 'CFBundleIconFile' -string $1.icns $1.app/Contents/Info.plist
plutil -insert 'NSHighResolutionCapable' -bool true $1.app/Contents/Info.plist

[C++] 266 実行ファイルからappファイルを作成 シェルスクリプト(引数あり)

[M1 Mac, Monterey 12.6.3, clang 13.0.0, SDL 2.26.2, ChatGPT Plus, NO IDE]

前回記事でMakefileで実行ファイルからappファイルを作成できるようにしましたが、そこだけ長ったらしくなるので引数ありシェルスクリプトにしてすっきりさせました。

chmodコマンドでアクセス権限を付与する必要があります。

# シバンは不要

mkdir $1.app
mkdir $1.app/Contents
mkdir $1.app/Contents/MacOS
mv $1 $1.app/Contents/MacOS
mkdir $1.app/Contents/Resources
cp ./images/$1.icns $1.app/Contents/Resources
plutil -create xml1 $1.app/Contents/Info.plist
plutil -insert 'CFBundleInfoDictionaryVersion' -string "6.0" $1.app/Contents/Info.plist
plutil -insert 'CFBundleExecutable' -string $1 $1.app/Contents/Info.plist
plutil -insert 'CFBundleIdentifier' -string "" $1.app/Contents/Info.plist
plutil -insert 'CFBundleName' -string $1 $1.app/Contents/Info.plist
plutil -insert 'CFBundlePackageType' -string "APPL" $1.app/Contents/Info.plist
plutil -insert 'CFBundleIconFile' -string $1.icns $1.app/Contents/Info.plist
plutil -insert 'NSHighResolutionCapable' -bool true $1.app/Contents/Info.plist
# oファイルから実行ファイル作成
$(TARGET):$(OBJS)
	$(COMPILER) -o $(TARGETDIR)/$@ $(OBJS) $(LIBRARY0) $(LIBRARY) $(LDFLAGS)
	cp $(TARGETDIR)/$(TARGET) $(TARGET)
	chmod 777 ./sh/makeApp.sh
	./sh/makeApp.sh $(TARGET)
# oファイルから実行ファイル作成
$(TARGET):$(OBJS)
	$(COMPILER) -o $(TARGETDIR)/$@ $(OBJS) $(LIBRARY0) $(LIBRARY) $(LDFLAGS)
	cp $(TARGETDIR)/$(TARGET) $(TARGET)
	mkdir $(TARGET).app
	mkdir $(TARGET).app/Contents
	mkdir $(TARGET).app/Contents/MacOS
	mv $(TARGET) $(TARGET).app/Contents/MacOS
	mkdir $(TARGET).app/Contents/Resources
	cp ./images/$(TARGET).icns $(TARGET).app/Contents/Resources
	plutil -create xml1 $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundleInfoDictionaryVersion' -string "6.0" $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundleExecutable' -string $(TARGET) $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundleIdentifier' -string "" $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundleName' -string $(TARGET) $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundlePackageType' -string "APPL" $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundleIconFile' -string $(TARGET).icns $(TARGET).app/Contents/Info.plist
	plutil -insert 'NSHighResolutionCapable' -bool true $(TARGET).app/Contents/Info.plist

[C++] 265 実行ファイルからappファイルを作成 plutilコマンド

[M1 Mac, Monterey 12.6.3, clang 13.0.0, SDL 2.26.2, ChatGPT Plus, NO IDE]

appファイルの中に格納するInfo.plistをMakefileで作成できるようになりました。

plutilコマンドはたまに使っていましたが、空のplistファイル作成からkey-valueを入力していくのは初めてでした。なおCFBundleExecutableなどのCFはCore Foundationの略です。NSは言わずと知れたNextstep。

これが最も正統な方法でしょう。少なくともFLTKのfltk-configよりも汎用性が高いです。XcodeでしたらInfo.plistは自動的に作成してくれるはず。

TARGETDIR = ./bin
TARGET = TetrisDX

# oファイルから実行ファイル・appファイル作成
$(TARGET):$(OBJS)
	$(COMPILER) -o $(TARGETDIR)/$@ $(OBJS) $(LIBRARY0) $(LIBRARY) $(LDFLAGS)
	cp $(TARGETDIR)/$(TARGET) $(TARGET)
	mkdir $(TARGET).app
	mkdir $(TARGET).app/Contents
	mkdir $(TARGET).app/Contents/MacOS
	mv $(TARGET) $(TARGET).app/Contents/MacOS
	mkdir $(TARGET).app/Contents/Resources
	cp ./images/$(TARGET).icns $(TARGET).app/Contents/Resources
	plutil -create xml1 $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundleInfoDictionaryVersion' -string "6.0" $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundleExecutable' -string $(TARGET) $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundleIdentifier' -string "" $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundleName' -string $(TARGET) $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundlePackageType' -string "APPL" $(TARGET).app/Contents/Info.plist
	plutil -insert 'CFBundleIconFile' -string $(TARGET).icns $(TARGET).app/Contents/Info.plist
	plutil -insert 'NSHighResolutionCapable' -bool true $(TARGET).app/Contents/Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleExecutable</key>
	<string>TetrisDX</string>
	<key>CFBundleIconFile</key>
	<string>TetrisDX.icns</string>
	<key>CFBundleIdentifier</key>
	<string></string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>TetrisDX</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>NSHighResolutionCapable</key>
	<true/>
</dict>
</plist>

[C++] 264 実行ファイルからappファイルを作成 fltk-config不使用

[M1 Mac, Monterey 12.6.3, clang 13.0.0, SDL 2.26.2, ChatGPT Plus, NO IDE]

FLTKソースコードのfltk-config.inの内容を確認しました。特殊なスクリプトを書いているわけではなくbashコマンドの組み合わせでした。

ただMakefileで一からinfo.plistを作ることはできず、あらかじめ作成しておいたinfo.plistをappファイル内にコピーするようにしました。

いまだにMakeは扱いづらいです。ChatGPTもさすがにMakefileには詳しくなく、自力で解決するしかないようです。

if test -n "$post"; then
    running=`uname`
    if test "$running" = "Darwin"; then
        # if FLTK targets MacOS+X11, apps need not be bundled
        if test `echo $LDLIBS | fgrep -c -e " -lX11"` = 1; then
            running=""
        fi
    fi
    case $running in
	Darwin)
	    echo Creating "'$post.app'" bundle for desktop...
	    id=`echo $post | tr ' ' '_'`

	    # Make the bundle directory and move the executable there
	    rm -rf "$post.app/Contents/MacOS"
	    mkdir -p "$post.app/Contents/MacOS"
	    mv "$post" "$post.app/Contents/MacOS"

	    # Make a shell script that runs the bundled executable
	    echo "#!/bin/sh" >"$post"
	    echo 'dir="`dirname \"$0\"`"' >>"$post"
	    echo 'exec "$dir/'"$post.app/Contents/MacOS/$post"'" "$@"' >>"$post"
	    chmod +x "$post"

	    # Make the simplest Info.plist needed for an application
	    cat >"$post.app/Contents/Info.plist" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<plist version="0.9">
    <dict>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleExecutable</key>
	<string>$post</string>
	<key>CFBundleIdentifier</key>
	<string>org.fltk.$id</string>
	<key>CFBundleName</key>
	<string>$post</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>NSHighResolutionCapable</key>
	<true/>
    </dict>
</plist>
EOF
	    ;;
    esac
fi
# oファイルから実行ファイル作成
$(TARGET):$(OBJS)
	$(COMPILER) -o $(TARGETDIR)/$@ $(OBJS) $(LIBRARY0) $(LIBRARY) $(LDFLAGS)
	cp $(TARGETDIR)/$(TARGET) $(TARGET)
	mkdir $(TARGET).app
	mkdir $(TARGET).app/Contents
	mkdir $(TARGET).app/Contents/MacOS
	mv $(TARGET) $(TARGET).app/Contents/MacOS
	mkdir $(TARGET).app/Contents/Resources
	cp ./images/$(TARGET).icns $(TARGET).app/Contents/Resources
	cp info.plist $(TARGET).app/Contents

[C++] 263 実行ファイルからappファイルを作成 fltk-config

[M1 Mac, Monterey 12.6.3, clang 13.0.0, SDL 2.26.2, ChatGPT Plus, NO IDE]

FLTKのfltk-configコマンドで実行ファイルからappファイルを作成できます。SDLアプリでも使えました。

appファイルの中に実行ファイルが格納されており、icnsファイルやInfo.plistをコピーすると完成になります。

fltk-configではなく正式な方法でappファイルを作成できるようにしたいところです。

# コンパイラ設定他
COMPILER = clang++
DEBUG = -g

# フラグ設定
CPPFLAGS = $(shell pkg-config sdl2 --cflags --libs) -std=c++11
LDFLAGS =

# includeパス(-I)
INCLUDE = -I./include -I/opt/homebrew/Cellar/sdl2/2.26.2/include \
		-I/opt/homebrew/Cellar/sdl2_ttf/2.20.2/include \
		-I/Volumes/DATA_m1/code/cpp/mylib/include \

# ライブラリ(-l)
LIBRARY0 = -lsdl2 -lsdl2_ttf

# ライブラリパス(-L)
LIBRARY = -L/opt/homebrew/Cellar/sdl2/2.26.2/lib \
		-L/opt/homebrew/Cellar/sdl2_ttf/2.20.2/lib \

# ソースファイル
SRCDIR = ./src
SRCS = $(shell find $(SRCDIR) -type f)

# オブジェクトファイル
OBJDIR = ./obj
OBJS = $(addprefix $(OBJDIR), $(patsubst ./src/%.cpp,/%.o,$(SRCS)))

# 実行ファイル
TARGETDIR = ./bin
TARGET = TetrisDX

# ICNSファイル
ICON = ./images/TetrisDX.icns
	
# cppファイルからoファイル作成 $<:依存ファイル
$(OBJDIR)/%.o: $(SRCDIR)/%.cpp
	$(COMPILER) $(CPPFLAGS) $(INCLUDE) $(DEBUG) -o $@ -c $<

# appファイル作成関連(FLTK以外のアプリにも使える)
POSTBUILD  = fltk-config --post

# oファイルから実行ファイル作成
$(TARGET):$(OBJS)
	$(COMPILER) -o $(TARGETDIR)/$@ $(OBJS) $(LIBRARY0) $(LIBRARY) $(LDFLAGS)
	cp $(TARGETDIR)/$(TARGET) $(TARGET)
	$(POSTBUILD) $(TARGET)
	mkdir $(TARGET).app/Contents/Resources
	cp ./images/$(TARGET).icns $(TARGET).app/Contents/Resources
	plutil -insert 'CFBundleIconFile' -string $(TARGET).icns $(TARGET).app/Contents/Info.plist
	rm -f $(TARGET)

# 全ソース・コンパイル&ビルド
.PHONY:all
all: clean $(OBJS) $(TARGET)

# oファイル・実行ファイル削除
.PHONY:clean
clean:
	rm -rf $(OBJS) $(TARGETDIR)/$(TARGET)

[C++] 262 SDL : テトリス落下スピード選択 その2 実装

[M1 Mac, Monterey 12.6.3, clang 13.0.0, SDL 2.26.2, ChatGPT Plus, NO IDE]

スタート画面でテトリスの落下速度を選べるようにしました。今の私のゲームスキルでSlowは20分、Normalは10分、Fastは5分程度でケリがつくように調整しました。

PS4コントローラーのR1ボタンかマウスクリックで選択できます。

selectButton関数の叩きはChatGPTが書いてくれました。

void App::Run()
{
	Uint32 lastTimeMs = SDL_GetTicks();
	auto lastTime = std::chrono::high_resolution_clock::now();

	bool bDone = false;
	while( !bDone )
	{
		GameInput gameInput = {};
		SDL_JoystickUpdate();

		// respond to events
		SDL_Event event;
		while( SDL_PollEvent( &event ) )
		{
			if(event.type == SDL_QUIT)
			{
				bDone = true;
			}

			// 落下速度ボタン選択(マウスクリック)
			if(event.type == SDL_MOUSEBUTTONDOWN)
			{
				mouseX = event.motion.x;
				mouseY = event.motion.y;
				SDL_Delay(10);
				selectButton(slowButton, normalButton, fastButton, mouseX, mouseY);
			}

			if(event.type == SDL_JOYBUTTONDOWN)
			{
				switch (event.jbutton.button){
					case 2:{	// □ボタン:スタート
						gameInput.bStart = true;
						start = std::chrono::steady_clock::now();
						scores = {};
						dates = {};
						fullDates = {};
						numAllScores = {};
						rank = 0;
						DrawPlayingCount = 0;
						GeneratorCount = 0;
						arr = {};
						break;
					}
					case 13:{	// 左ボタン
						gameInput.bMoveLeft = true;
						break;
					}
					case 14:{	// 右ボタン
						gameInput.bMoveRight = true;
						break;
					}
					case 1:{	// ○ボタン:反時計回り回転
						gameInput.bRotateClockwise = true;
						break;
					}
					case 0:{	// ×ボタン:時計回り回転
						gameInput.bRotateAnticlockwise = true;
						break;
					}
					case 12:{	// 下ボタン:一気に落下
						gameInput.bHardDrop = true;
						break;
					}
					case 11:{	// 上ボタン:徐々に落下
						gameInput.bSoftDrop = true;
						break;
					}
					case 10:{	// R1ボタン 落下速度ボタン選択
						buttonCount++;
						if (buttonCount % 3 == 1){
							fastButton.selected = true;
							normalButton.selected = false;
							s_initialFramesPerFallStep = 24;

						} else if (buttonCount % 3 == 2){
							slowButton.selected = true;
							fastButton.selected = false;
							s_initialFramesPerFallStep = 48;

						} else {
							normalButton.selected = true;
							slowButton.selected = false;
							s_initialFramesPerFallStep = 32;
						}
						break;
					}
					default:{
						cout << "default" << endl;
						break;
					}
				}
			}
		}
		
		// FPS算出のために1フレーム時間を計算
		Uint32 currentTimeMs = SDL_GetTicks();
		Uint32 deltaTimeMs = currentTimeMs - lastTimeMs;
		lastTimeMs = currentTimeMs;
		HP_UNUSED( deltaTimeMs );
		
		auto currentTime = std::chrono::high_resolution_clock::now();
		auto deltaTime = currentTime - lastTime;
		std::chrono::microseconds deltaTimeMicroseconds = std::chrono::duration_cast<std::chrono::microseconds>(deltaTime);
		float deltaTimeSeconds = 0.000001f * (float)deltaTimeMicroseconds.count();
		lastTime = currentTime;

		mGame->Update(gameInput, deltaTimeSeconds );

		mRenderer->Clear();
		mGame->Draw(*mRenderer );
		mRenderer->Present();
	}
}
void selectButton(Button& slow, Button& normal, Button& fast, const int mouseX, const int mouseY) {
    slow.selected = false;
    normal.selected = false;
    fast.selected = false;

    if (mouseX >= slow.rect.x && mouseX <= slow.rect.x + slow.rect.w &&
        mouseY >= slow.rect.y && mouseY <= slow.rect.y + slow.rect.h) {
        slow.selected = true;
        s_initialFramesPerFallStep = 48;
        cout << "slow clicked" << endl;

    } else if (mouseX >= normal.rect.x && mouseX <= normal.rect.x + normal.rect.w &&
        mouseY >= normal.rect.y && mouseY <= normal.rect.y + normal.rect.h) {
        normal.selected = true;
        s_initialFramesPerFallStep = 32;
        cout << "normal clicked" << endl;

    } else if (mouseX >= fast.rect.x && mouseX <= fast.rect.x + fast.rect.w &&
        mouseY >= fast.rect.y && mouseY <= fast.rect.y + fast.rect.h) {
        fast.selected = true;
        s_initialFramesPerFallStep = 24;
        cout << "fast clicked" << endl;
    }
}

[C++] 261 SDL : テトリス落下スピード選択 その1 ChatGPT

[M1 Mac, Monterey 12.6.3, clang 13.0.0, SDL 2.26.2, ChatGPT Plus, NO IDE]

これまで開発してきたテトリスはベーシック版として、多機能版を別に開発することにしました。

まずはテトロミノの落下スピードを調整できるようにします。ボタンを3つレンダリングしています。

ChatGPTにヘッダファイルを見せた上でコードの作成方法を聞いてみました。

Q: <Game.hは省略> 以上のGame.hを踏まえて落下スピードを3段階に設定するにはどうしたらよいですか?

Tetrisの落下スピードを3段階に設定する場合は、Gameクラス内に落下スピードを管理する変数を追加し、GameInput構造体にボタン入力を追加して、それに応じて落下スピードを変更するようにUpdatePlaying関数を修正する必要があります。

以下は、例としてUpdatePlaying関数を修正したコードです。ここでは、bSlow、bNormal、bFastの3つのフラグ変数をGameInput構造体に追加して、それぞれがtrueの場合に対応する落下スピードを設定しています。

void Game::UpdatePlaying(const GameInput& gameInput) {
    if (gameInput.bPause) {
        m_gameState = kGameState_TitleScreen;
        return;
    }

    // 落下スピードの設定
    int framesPerFallStep;
    if (gameInput.bSlow) {
        framesPerFallStep = 48;
    } else if (gameInput.bNormal) {
        framesPerFallStep = 32;
    } else {
        framesPerFallStep = 16;
    }

    // 落下フレーム数の計算
    m_framesUntilFall -= 1;
    if (m_framesUntilFall == 0) {
        m_framesUntilFall = framesPerFallStep;
        m_activeTetromino.m_pos.y += 1;
        if (CheckTetrominoCollision(m_activeTetromino)) {
            // 衝突した場合、テトロミノをフィールドに追加する
            AddTetronimoToField(m_field, m_activeTetromino);
            // 行を消去する
            int numLinesCleared = ClearFullLines(m_field);
            m_numLinesCleared += numLinesCleared;
            m_level = m_numLinesCleared / 10;
            // 新しいテトロミノをスポーンする
            if (!SpawnTetromino()) {
                m_gameState = kGameState_GameOver;
                return;
            }
        }
    }

    // 入力に応じた処理
    if (gameInput.bMoveLeft) {
        if (!CheckTetrominoCollision(m_activeTetromino, -1, 0)) {
            m_activeTetromino.m_pos.x -= 1;
        }
    }
    if (gameInput.bMoveRight) {
        if (!CheckTetrominoCollision(m_activeTetromino, 1, 0)) {
            m_activeTetromino.m_pos.x += 1;
        }
    }
    if (gameInput.bRotateClockwise) {
        if (!CheckTetrominoCollision(m_activeTetromino, 0, 0, 1)) {
            m_activeTetromino.m_rotation = (m_activeTetromino.m_rotation + 1) % Tetromino::kNumRotations;
        }
    }
    if (gameInput.bRotateAnticlockwise) {
        if (!CheckTetrominoCollision(m_activeTetromino, 0, 0, -1)) {
            m_activeTetromino.m_rotation = (m_activeTetromino.m_rotation + Tetrom