0

Is there any way to simplify this code, and make it continuable still?

set /a food=%random% %% 6 + 1
if %food%==1 (set foodtype=bread)
if %food%==2 (set foodtype=apple)
if %food%==3 (set foodtype=steak)
if %food%==4 (set foodtype=banana)

etc.

I don't know alot of batch, but i'm expecting something along the lines of this:

set /a food=%random% %% 6 + 1
 if food = (1, 2, 3, 4) (set foodtype bread, apple, steak, banana)
aschipfl
  • 33,626
  • 12
  • 54
  • 99
  • 4
    Possible duplicate of [Switch statement equivalent in Windows batch file](https://stackoverflow.com/questions/18423443/switch-statement-equivalent-in-windows-batch-file) – Nico Haase Apr 08 '19 at 14:36

5 Answers5

3

As an alternative, you could also use a list:

@echo off
setlocal 
set count=0
set "foodlist=bread apple steak banana"
for %%a in (%list%) do set /a count+=1
set /a tok=%random% %% %count% + 1
for /f "tokens=%tok%" %%a in ("%foodlist%") do set "foodtype=%%~a"
echo/%foodtype%

(Advantage: you can modify the list (remove or add items) "on the fly" (e.g. during the game) without adapting the code)

Stephan
  • 53,940
  • 10
  • 58
  • 91
2

You could use pseudo-arrays (as arrays are not really supported).

setlocal EnableDelayedExpansion
set "arr_foodtype[0]=bread"
set "arr_foodtype[1]=apple"
set "arr_foodtype[2]=steak"
set "arr_foodtype[3]=banana"

set /a food=%random% %% 4

set "foodtype=!arr_foodtype[%food%]!"
jeb
  • 78,592
  • 17
  • 171
  • 225
2

Another, shorter approach:

@echo off
setlocal EnableDelayedExpansion
set "foodList=bread apple steak banana "

set /A food=%random% %% 4

set "this=%foodList: =" & (if !food! equ 0 set "foodtype=!this!") & set /A "food-=1" & set "this=%"

echo %foodtype%

This solution uses the same self-expanding code method shown in LotPing's answer...

Aacini
  • 65,180
  • 12
  • 72
  • 108
1

Similar method to Stephan's answer converting the list to an array, but using sort of self expanding code.

:: Q:\Test\2019\04\08\SO_55575835.cmd
@Echo off&SetLocal EnableDelayedExpansion

Set i=0&Set "foodtypes= bread apple steak banana"
Set "foodtypes=%foodtypes: ="&Set /a i+=1&Set "foodtypes[!i!]=%"

set /a food=%random% %% %i% + 1
set "foodtype=!foodtypes[%food%]!"

set food

Sample output:

>  SO_55575835.cmd
food=2
foodtype=apple
foodtypes[1]=bread
foodtypes[2]=apple
foodtypes[3]=steak
foodtypes[4]=banana
0

What about a multi-line string approach (the blank lines in the code are mandatory):

@echo off
set /A "FOOD=%RANDOM%%%4+1"
for /F "tokens=1*" %%I in (^"
1 bread^

2 apple^

3 steak^

4 banana^

^") do if %%I equ %FOOD% set "FOODTYPE=%%J"
echo %FOOD%: %FOODTYPE%

Sample output:

2: apple

By the way, set /a food=%random% %% 6 + 1 assigns a value from 1 to 6.

aschipfl
  • 33,626
  • 12
  • 54
  • 99