11/05/2015

Programming logic in a nutshell. Soda Machines

First thing you need to do is think of how you would want a program to work. Like everything that it does, and the steps it has to do certain taskes and how it can do multiple different options.

One example of this would be like a soda machine, You have several options to select from and if the current balance is lower than the required balance it will not dispense. But if it does have the right amount or over and there is none there than it doesn't dispense. But if there is enough there and you are over the required balance then it dispenses change.

But if you use a card it checks with the account holding corperation if you have enough and if you don't it doesn't dispense and sends a message to the screen. But if you do have enough it dispenses.

That soda machine does have programming involved with it, and that is the mindset you need to have. Each item selection is a array of items. A array is something common in programming that is basically storage values and can have multiple dimensions.  Meaning a X Y & Z basically.

So you can have a array named SodaTrays which stores the required amount of money, and the number of soda's currently in the slot, and a nonmodifyable number of soda's that are loaded each time it is stocked.
You would have it be a 2d array which would mean a x & y and the Y value would just refer to the individual soda array tray.

So you have 8 different options with this soda machine, 3 pepsis , 4 mountain dew, and 1 water.

C++ example of the water tray array data values:

amount currently in: cout << SodaTrays(1,8); output:  7
cost:  cout <<"$"<<  SodaTrays(2,8); output: $1.00
max stored: cout << SodaTrays(3,8); output : 12

The importance of having a max stored value is to reset the current in once stocked, if you ever wondered why a machine ate your money and spit out nothing it is because someone didn't stock it correctly usually, or someone hacked the machine.

So each time a purchase is made the current in value needs to be subtracted from and once it hits less than 1
then it needs to loop back into option selections til the user makes a correct selection or asks for their money back which it dispenses the equal amount in from the change dispenser or dollar depending on how the mahcine is made.


All of those IF conditions can be if statements or they can be switch case statements depending on how you want your application to work. Each object in the soda machine can be a object a blue print of how it works and storage values. Such as the coin dispensor can be different from the coin slot, and the buttons are multiple objects that you would re-use code for with different values. Some code can be re-used so a object class is created to store this data which is a seperate file from the main program that is read and included into it.

So instead of a array you can also make each option its own object with it's own functions and its own data, which can be private, secure, or public. Public allows modification from other sources, private doesn't, and secure is difficult to explain as different langauges handle it differently I won't discuss it. You can also have objects that inherent from other objects which means you can create entirely different objects from the same source object.

This would be like if you made a object for animal, well birds, bugs, mamals, fish, and reptiles could inherent from that object and goldfish can inherent from fish, and clown fish can inherent from fish. Goldfish would hold different data values than clown fish such as diet values. This is a example of inherents. So for a soda machine you can have a object for SodaSelectOption and you can have a object for PepsiSelect which inherents from SodaSelectOption which would hold all the same data as every other object but pepsi can have its own data values. The PepsiSelect can store data for each tray and lets say want it to display it's logo and it be the only item to do that, then we can have a seperate function that accesses the display and draws it there.

The things that would be stored in the SodaSelectOption object would be public: int itemcount; double cost; private: int maxItemCount

A int is a integer value, meaning whole number values. A double is a 0.00 formatted number value which means it can only store a int value followed by 2 decimal values if you want more decimal values you will need a float, which is pretty much the same kinda.

Next thing you would need to create is a function that dispenses the remaining change back to the customer.

There is many ways to do this from creating doubles in the main program file to functions with return values. The int would be the easiest way but not nessarily a good way.

First you will need to create a function delaration

int returnBalance(double,double);

Then you will need to create the actual function with a return value

int returnBalance(double currMoney, double costI)
{
      return currMoney-costI;
}

The next thing you will need to do is code the coin dispensor to check for coins and dispense them very similar to checking for option selection but with coins. So no need to go over that.

so you would want your main program to do something like this at the end of each transaction

CoinDesp.dispense(returnBalance(Cashin.amount, pepsi.cost));

What the whole idea is you program a loop function that dispenses till the amount is reached starting out with basic if statements.

Example of function in CoinDesp object

void dispense(int returnA)
{
         while(returnA > 0)
         {
                if ( returnA > 25 && self.check('q') > 0)
                   {
                           self.dispense('q');
                           returnA -= 25;
                   }
                else if ( returnA > 10 && self.check('d') > 0)
                   {
                           self.dispense('d');
                           returnA -= 10;
                   }
                else if ( returnA > 5 && self.check('n') > 0)
                   {
                           self.dispense('n');
                           returnA -= 5;
                   }
                else if ( returnA > 1 && self.check('p') > 0)
                   {
                           self.dispense('p');
                           returnA -= 1;
                   }
          }
}

What this is doing is checking if the remainder amount is greater than the coins value and if there is a coin of that value, then dropping the coin  with a function based off a character value in the parameter then subtracting the coin value till the remainder value is . && = and in a if statement.

That is pretty much it and you would reuse this for coin return, with the return value = the amount of money put in.

No comments :

Post a Comment

Please be kind to others, and my self.

Rss Feed

Undeadbobop's blogs

↑ Grab this Headline Animator

FeedBurner

I heart FeedBurner

Labels

#e3 #nintendo $oft 1 2 3 submit pro 10 10 ways 2 200 2014 2015 25th Anniversary 2600 2d 3:4 ratio 3.14 343 360 3d 3d modeling 3ds 3DTin 5 5 nights 64 7 7th guest 8 90 abandon abandonware abuse accessories accounts Ace acer acer 11 achievements acting ad ad free adapter adblock add on admin adreno Adriano ads adsense adv adv menu advance advance menu system adventure advertisement advertisers affordable AI airplane algorithms alone alpha AlphaOmegaSin alternative always amazing amazon amazon app store amd America android Android disable ads in games angry animal animate animated Animation animations anime API app app developer in detroit Michigan app development appegg Apple application apps appspotr arcade arch ARM array art art work ashleey assault assets asus AT&T atari atgames ATOM ATT attack audience audio auto AVGN away back back links background Backlinks bad badges bag bags ball balls ballz Balmer bandicoot banks bar base basic basics basketball Batdan battery battle. DLC. link bayonetta beating bed Beginner Bernie best Bethesda's New Review Copy Policy bfxr bgoat big Bill bing bios bioshock birds birthday bit bites black blackberry Blackjack Blackmail blade blast blender block blockstorm blog blogger bloodmoon blue Bluetooth blur bo bo's Boarding bobop book boom bored borkin button boxes boy breaks brick bricks bride broke broken Bros brotherhood browser bsd buck bucks bug buggy bugs build Bully bundle bungie bus bus driver 2d experience rush bust buy C# C# XNA Gamestudio c++ C++. directx c++. html c64 cable Call of Duty can can't canceled candy capcom capture car card cards care caret-t Cast caster cat cb3-111 CD chair challenges change character cheap cheaters cheating checking chimp chimpmail choice Chrome chrome book chrome cast chrome os chrome web browser chromebook chromebooke chromecast app chromeos Cities clara clara.io Classic classical clearance client clone cloud applications cloud computing club cocoonjs code code envy coding coin college color colour comedy command comments commercial community Comparison compatibility competitive market complaints complete roms list computer computer AI Computers connect connect 4 connecting cons console Consoles constroller construct construct 2 construct 2 gaming engine construct 2 gaming engine plugin construct 2 holiday plugin construct 2 plugin construct 2 time and date plugin construct 3 construct2 content contest controller Controller Pro Controller Pro U controls convict convict gaming Cool Copy corruption Corruption in gaming news journalism Corsair cost costume couch counter counter strike counter strike condition zero counter strike global offensive counter terrorists counterstrike court cpu crafting crap crash crazy crd create creating creation creativity Creators credit crossing crush crusher csgo css ctf cubes cue curse cursor custom customization templates Cyanara cylinders daniel date object dbz DDOS dead deathmatch delay dell Deluxe demo depression descriptions desert design desktop desura Detroit develoming develop Developers developing development development kit dial dialup died difficult dig Digital Direct directx disabilities discontinued Discs dishonest disney DLC DMCA DMZ DNS do Documentations doesn't work Dogs dollar done Doom dos down downfall download drag Dragon dragonball drawing Dream Dreamcast Dreamout dreams Drive driver DRM drug store ds duckduckgo dug dumb dumbphone dust button DVD e3 EA East Detroit easter egg Eastpointe eastside easy ebaulms Eco edge Edge gamepad Edition education effects electric electronic email email list eminem Emio emu emulation emulation station emulator emulators Encore end engine engines enlightenment entertainment environment Eshop ethical practices ethics EULA event ever evil example exclusive expand experience expired site exploit eyes F.E.A.R. face Facebook Facebook account hijack faceplate fail fall fallout fallout 4 family famous fan art Fanboy fast FCC fear features feed Feeds fees Feminism feminist file fill fire firefox firefox marketplace firefox os firewall firm firmware first Fishing five fix flash flaw flickr Flowcharts font fonts Footage football for forget forgotten domain fortress fox fps frame frame rate framework fraud freddy's free free money free software free to play freeware fried friend friendship full fullscreen fun functions fx galaxy gambling game game asset pack game development game development companies Game development companies in detroit game development companies in michigan game development tools game engines game list game maker Game review gameboy gamegear gameinformer gamejolt gamemaker gamepad gameplay GamePop Gamer gamers games Gamestick gamestop gaming gaming assets gaming easter eggs garrys mod gas Gates GBA gears geek gender Genesis Genesis Ultimate Portable Game Player get gif gimp give give away glitches glove gnu GNU/Linux go God Gold Golden good goofed google google chrome google play google+ googleplay gore gorescript GPL gpu Grammar grand grandtheft auto graphics gray greed greedy green grey grid groom gta guestbook guide gunners h2100 hackers hacking half halflife halflife 2 halflife 3 halflive halo Halo 2 Halo 2 Anniversary Halo legends handheld hard hardware harmony hawk HD HDMI head headphones headset hedgehog hell help hexen highschool highscore hijack hl1 hl2 holidays home homebrew homicide honest hook hosting hotel hotmail How to HP HTC Vive HTML HTML5 humble humor hyperkin hypermart ID ID Tech IDE IE IGN illegal image images Impact Impressions improves index color indie indiedb industries industry information informer inn input input device insomnia Install instinct institute instructors intentional internet internet explorer internet radio interview introduction ion iOS IOS 9 ip ip address Iphone Irate Irategamer irish iron is island isometric ISP issue issues IT itch.io item items iwork jack Jaden smith jam james Japanese java javascript jelly jif jiggly puff Jim jiminquestion job joint joke jokes jolicloud journalism joytokey js k70 Kainy Kart key keyboard keystation kick kickstarter killed killstreak Kim Jong-un kingdom hearts kitten kitty Knuckles kongregate Kotaqu kryo lag lan land Las Vegas lash Last Launch law learning legacy collection legal length Lenovo lerp level LG LGBT liar liars lib GDX Library libretro lies life light lilly link Linksys linux lithium live load local lock locked logic logmein lonely loop lost temple text adventure low Lucid ludei Lycoming mall lynx mac machine macomb community college macombacon Mad Mad over mail mail chimp make make money fast makefile maker making manager manifest map mapping maps Mario Mario Galaxy Mario Kart Mario kart 8 deluxe Marker Marker sprite font market market share marketing marriage married mass email subscription service master mechanical media Megadrive megaman melody menu menu system menus meow Metro Michigan micro Micro-transactions microsd Microshaft Microsoft Microsoft store in michigan Microsoft wordpress microusb midi mii miitomo mike mike v milkshape 3d mind minecraft mini mini game minimum wage minish cap misleading misleads mobile moddb modding mode modeling models mods mogotxt moltres monetize money monitziation Monodevelopment monogame montization monzilla Moon Moore Mortal Kombat Mote mouse movie Movies multiplayer Mupen64 murder musial music mussels Mysterious mystic n64 Navel nba need nerd nes Nes classic net netlink netplay network networking new newgrounds news nexon Next nfl Nights Nintendo Nintendo 64 Nintendo Switch nitch no noncommercial North Korea not notepad++ November now NSA nurse nvidia NX nyan o'reilly OC Ocarina odd odk of off office offline oh Ohio Old Omega On off switch one Onedrive online opengl operation optimization options os OS X OSX out out of order out of service out there ouya overscan p2p p2w pack pad paid paint pandora panic papagayo paper weight Paradise parody party patch Paths pause pay pc peer peerblock Performance Personal Peter pewdie pewdiepie phishing phone phones photo Photoshop php pi piano picture pie pin pink pixel art plagiarism plants plants vs zombies plastic plate platformer platinum play player players playing Playstation playzool please plugins plus poke balls pokemon Pokemon go poker pokestops Pokken tournament Pokken tournament Pikachi controller pool pool table popular populate port portable posts power practice practive pre-order premade presentation preview price Privacy Badger private pro problems program programming Projared project promises promote Promotion provider ps1 PS2 ps3 ps4 public purple Pygames Pyshell Python Python Fiddle qlife quake qualcomm quest quick rack radio raffle Rage ram random rant rare raspberry pi raspbian rate razer Razer Forge TC recommend Record recording red red cherry redit Released Remix remote remove renaissance repair representation require resources rest retirement retroarch Retrobit retrode Retroduo Retrogen retron 5 Retropi retropie retry review ReviewTechUSA rewards rigging rip ripoff ripper river road roads Rock Rock Paper Shotgun Rockstar rolfe RollApp rom roms Roseville routing RPG RSS rush saga sale same Samsung Saturn save saving Scam Scholarship scirra score screen screen sharing screencastify screenshot Screenshots screw script scroogle scum sdl seamless search Secret security seed Sega sega dreamcast sega genesis Sega Genesis Ultimate Portable Game Player sega master system Sega Saturn SEO sequel server servers service set settings setup seven card Shaft shapes share this shareware sharing shield Ship shit shockwave shooter shop shot signs simple Sin site skate Skateboard skeleton SkyDrive slavery sleep slip slumber small smart smartboy Smash SMM smo snapdragon snapshot snes social media soda software solitions song sonic Sony sound sounds source sparks sparky spartan specialized spell check spelling spheres spoiler free spotify sprite Sprite font sprite sheet spritefonts spriter spyro spyware SQL stakes Star Starling starter steam steam box Steam controller steam gamepad steam os steamos sterling steve scott Steven Stolar stop store storm strategy game strategy guide stream streaming strike stud studio studios styles subscribe success Sucks summer Sun super Super Mario Super Mario Maker super mario maker bugs super mutants Super Smash Bros support SWF Switch SWJ sync system systems table tac tags Tails miles tamagotchi target target marketing tax taxes teachers teaching team team fortress 2 crafting teams Tech tegra template templates temple run temple run 2 terrible terrorists testing text Text adventure textbase texture packer tf2 The Interview the king's league odyssey The Letter the world theft Things this thoughts thunder tic tic tac toe tile tilemap time time date tin titles to toe tony Tony Hawk tool tools top top 10 top 5 topic matter torque Total Media touch touchpad Town toys trading travel traveling tree TreeFall Studios Treehouse trees trirectimo tube Tuner tutorial TV Twitch Ubisoft Ubuntu UML undeadbobop understanding news feeds unearthing unethical bots union unity unreal unusual up update USA usb usb 3.0 usb y use useless users Valor valve valve editor hammer VBA vc Vegas Vengeance version video video game Video game art video games videogame vidme view views villager vimeo vine vintage Virtual virtual console virtual reality virus Visio VLC voice volume voxel VR review vs wall wallet wan ware Watch Watchdogs wave wayback web web assembly web design web server web server ultimate webgl webhosting webmaster website websites websitesubmit webstorage webstore wedding what is my ip white Wii wiiu will Smith windows windows 8 Wino wireless Woofle word wordpress work workaround workshop world worst WoW WoW! XBL XBLA xbone xbox xbox 360 xbox gamepad xbox one xboxdone xboxone xeno xenoblade xhml xl xml xna you yourself youtube zapdose zelda Zelda breath of wild Zilla zip zombie zombie panic zombie panic source zombies

promotions