البرمجة

تجنب القيم السالبة في لعبة دفعات الدفع

To prevent variables from becoming negative when buying items in your batch game, you can add a check to ensure that the player has enough money before subtracting the cost of the item. Here’s how you can do it:

batch
@echo off setlocal enabledelayedexpansion rem Initialize money variable set money=100 :shop_menu cls echo Money: %money% echo. echo 1. Buy Sword (30$) echo 2. Buy Shield (20$) echo 3. Exit echo. set /p choice="Enter your choice: " if "%choice%"=="1" ( if %money% geq 30 ( set /a money-=30 echo Bought Sword for 30$ ) else ( echo Not enough money! ) pause goto shop_menu ) else if "%choice%"=="2" ( if %money% geq 20 ( set /a money-=20 echo Bought Shield for 20$ ) else ( echo Not enough money! ) pause goto shop_menu ) else if "%choice%"=="3" ( echo Exiting shop... pause exit /b ) else ( echo Invalid choice! pause goto shop_menu )

In this example, the if %money% geq 30 (where geq stands for “greater than or equal”) checks if the player has at least 30$ before buying the sword. If the player doesn’t have enough money, it displays “Not enough money!” and doesn’t allow the purchase to go through. Adjust the values and items as needed for your game.

المزيد من المعلومات

لحماية المتغيرات من أن تصبح سالبة في لعبتك بدفعات الدفع، يمكنك استخدام شرط للتحقق مما إذا كان المبلغ المطلوب للشراء يتجاوز الرصيد المتاح. في هذه الحالة، يمكنك إما منع الشراء أو تقديم رسالة تعلم المستخدم بأن الرصيد غير كافٍ.

لتنفيذ هذا في دفعة الدفع، يمكنك استخدام الشرط التالي في الأمثلة المعطاة:

batch
if %money% lss 0 ( set money=0 )

هذا الشرط يحقق إذا كانت قيمة المتغير money أقل من صفر (lss 0). إذا كان الشرط صحيحًا، فإنه يقوم بتعيين قيمة money إلى صفر. تأكد من وضع هذا الشرط في المكان المناسب في برنامجك لضمان عدم تجاوز الرصيد إلى الأرقام السالبة.

أيضًا، لتجنب أخطاء الإدخال، يمكنك استخدام دالة للتحقق من صحة الإدخال. مثلاً:

batch
:input_validation set /p choice="Enter your choice: " if "%choice%"=="1" goto buy_sword if "%choice%"=="2" goto buy_shield if "%choice%"=="3" goto exit_shop echo Invalid choice! goto input_validation

في هذا المثال، يتم تكرار طلب الإدخال في حالة تقديم اختيار غير صالح، مما يضمن أن يتم اختيار إحدى الخيارات الصحيحة.

باستخدام هذه الإجراءات، يمكنك تحسين أداء لعبتك وتجنب القيم السالبة للمتغيرات.

زر الذهاب إلى الأعلى