Community Tip - You can change your system assigned username to something more personal in your community settings. X
Recently, I was in the position of trying to explain to a 6- and 8- year old how to play the board game Battleship. (Kids from my generation had commercials that seemed to explain the basics of the game fairly well.) While trying to explain the concept of the grid to them and search algorithms, I couldn’t help but wonder, “How could this be done in Mathcad Prime?”
This month’s challenge, should you choose to accept it, is fairly open-ended: simulate various aspects of the Battleship game in Mathcad. Here are some suggestions:
Write a program that will place the ships on the ocean grid. The ships must be placed horizontally or vertically; no diagonals. Ships can’t overlap one another. Do you place the ships randomly or according to some kind of optimized algorithm?
Alternatively, can you use Advanced Input Controls to allow the user to place the ships on the ocean grid?
Display the placement of the ships using the plotting capability.
Display the hits and misses on a plot or chart.
Can you program Mathcad Prime to run through a number of iterations of placing and hunting ships, and then evaluate statistics on number of shots needed to sink the fleet?
Again, these are just suggestions. Feel free to create a worksheet that tackles any aspects of the classic board game. Do as little or as much as you like. Also, your worksheet should stand on its own; a stranger should be able to open it and understand what it’s for.
For the sake of this challenge, we will use the following ships:
It’s a kids game, so have fun with this!
Find the Mathcad Community Challenge Guidelines here!
Just wanna say that if the Community can collectively figure out the "keep track of previous shots without overwriting the history" problem in Mathcad, then the people contributing to that will be immortalised in Mathcad history as super-geniuses. 'cause I spent a lot of time trying to figure that out for the Mathcad Game Gallery, to no avail.
@DJNewman wrote:
Just wanna say that if the Community can collectively figure out the "keep track of previous shots without overwriting the history" problem in Mathcad, then the people contributing to that will be immortalised in Mathcad history as super-geniuses. 'cause I spent a lot of time trying to figure that out for the Mathcad Game Gallery, to no avail.
Could you please further explain what you mean, Dave, preferably with an example?
Stuart
David and I were talking about having a person be able to play Battleship - call their guesses - using Advanced Input Controls.
For example, let's say I use a couple drop-downs to select B5.
I am informed it's a miss.
I call out H2. It's a miss.
I call out J9. It's a hit.
Try to do that in Mathcad Prime. That's what David and I were talking about.
@DaveMartin wrote:
David and I were talking about having a person be able to play Battleship - call their guesses - using Advanced Input Controls.
For example, let's say I use a couple drop-downs to select B5.
I am informed it's a miss.
I call out H2. It's a miss.
I call out J9. It's a hit.
So, you want a memory of previous selections?
@DaveMartin wrote:
Try to do that in Mathcad Prime. That's what David and I were talking about.
I'd love to, but I'm a lowly Mathcad Express user. None of your fancy advanced controls for me! 🙂
Might it be possible to update a file after each guess, either in Mathcad proper or inside a component?
Failing that, perhaps use an undocumented feature that's been hanging around since the original Mathcad days? ISTR, it worked during my MP11 trial.
IIRC, I have another version floating around that allows deletion from such a list, but I've got no idea where it might be lurking in my worksheet collection.
Stuart
Still not being quite sure of the requirements for keeping track of moves, but is this kind of thing along the right lines?
-----------------------------------------------
I got bored, or perhaps I got distracted by a squirrel and lost track(!) of my train(#) of thought, I can't remember.
Less than perfect, but perhaps sufficient to be a starting point for those with Advanced Controls to play with?
Start of Game:
After several moves:
Stuart
(#) When I say "train" ...
Not even the Technics version.
Stuart,
You addressed this to David, but I will reply (seeing as I wrote the challenge). You asked about the requirements of keeping track of the moves, and whether something was along the right lines.
This challenge was written to be open-ended: simulate in Mathcad Prime any aspects of the board game Battleship. There aren't traditional requirements like in a regular software project. If you're happy with it, it's fine.
When I write these, I try to keep them so that anyone who wants to participate can invest maybe a couple hours in it and share their work. It's meant to be fun. In this case, if it captures any part of Battleship game play, it's along the right lines.
Dave
Once a kind soul at PTC would be willing to reveal how to read and write matrices via the API (see this thread: API - Load MathCAD Matrix with JScript) we could use a Prime input matrix as the games memory which can be manipulated further down via scripts in advanced controls.
Otherwise an external file which is read in on recalc could do the job.
Unfortunately the advanced controls are too limited and not really good implemented to create a nice game which makes fun to play (I already noticed that in the "create a game challenge" a while ago). When implementing a board game it would only make sense if we could click directly on the board to place a piece. Its boring to have to type in board coordinates or chose them via drop downs.
We could create a game board consisting of 100 buttons with input values, but unfortunately we cannot change font size, color or background color here. let alone using an image for the button display. Furthermore its annoying that every time you click a button the plus sign for the input appears. IMHO this should only happen if I actively chose to edit the control. And of course we should be able to lock controls.
So I consider Prime not to be the tool to create a nice game. Its rather like asking "who is best in driving in a screw using just a hammer" and the only answer can be: “Put down the hammer and use a screwdriver!” ;-(
But if PTC were to incorporate into Prime some of the features needed to develop appealing interactive games, serious professional applications would also benefit enormously.
Frog Wars.
Now that it's not just me who wants such things, I'm hoping that peer pressure from within PTC can hasten the implementation of a Plot Component whose behaviour *at least* replicates that of Mathsoft Mathcad 11..15. That includes subplot selection and the ability to assign a Plot Component to a function (that thus allows inputs to the component via a function call -- a major omission, IIRC, from Mathcad Prime Advanced Controls).
Memoization has been mentioned a few times. Here's one example.
https://community.ptc.com/t5/Mathcad/Feature-Request-Mutual-Recursion/m-p/254273
I guess the other mentions must have disappeared along with the Collaboratory, partial application and recursive local functions.
I wonder if Python scripting can perform some form of memoization?
https://www.geeksforgeeks.org/python/memoization-using-decorators-in-python? I'm not sure how much use it would be, though, without being able to wrap a function definition around a component.
Stuart
Well, the problem is indeed Maslow's hammer. But since we also have other tools at our disposal, we shouldn't use the hammer for tasks for which it is completely unsuitable (not even as a challenge).
But PTC is free to improve its hammer and turn it into a useful multifunctional tool that can at least be used to create simple games (yes, OK, let me dream on...). As I said, more serious applications would definitely benefit from this too.
Oh, by the way, when I think of Clarke's third law, it occurs to me that I can't see anything magical in Prime at all.
@Werner_E wrote:
Well, the problem is indeed Maslow's hammer. But since we also have other tools at our disposal, we shouldn't use the hammer for tasks for which it is completely unsuitable (not even as a challenge).
Oh, I don't know. Half the fun is in the challenge. Of course, half the hair-loss is too, but ...
I'm still slightly bemused by how much I can learn about different areas of application from trying to do something 'challenging' in Mathcad.
That's why I have 590 tabs open in Chrome, plus 12 in DuckDuckGo.
And it's also why I have 7 worksheets open in Mathcad Express 10 and 5 in Mathcad Express 11 -- I'd have more open, but things are slow enough with just that few on the go in parallel.
@Werner_E wrote:
But PTC is free to improve its hammer and turn it into a useful multifunctional tool that can at least be used to create simple games (yes, OK, let me dream on...). As I said, more serious applications would definitely benefit from this too.
As long as they keep The Committee for Feature Removal and the The Department for Creative Nannyware away from 'improving' Mathcad ...
Otherwise, we run the risk of the hammer morphing into something safer for novice Tiny BASIC programmers.
Instead of a slightly more useful hammer.
Or one of those hammers with an explosive nail gun built into the hitty bit. 😈
@Werner_E wrote:
Oh, by the way, when I think of Clarke's third law, it occurs to me that I can't see anything magical in Prime at all.
Oh, I do. I still think Mathcad is one of the nicer development environments for doing maths work in (and Mathcad Prime's matrix entry method is better than the original Mathcad's (IMO)).
Stuart
Yes, I definitely agree that it can be fun to figure out how to perform brain surgery with a hammer or lay and connect electrical wiring by using just a screw driver. But despite all your efforts and the associated learning effects, the results would probably be quite unsatisfactory. And in my opinion, the games in Prime that have been posted here in the last few challenges have shown this and the limitations when it comes to interactive elements (which are essential for games).
And yes, I would very much welcome it if Prime were to develop further in this regard. However, like you I also fear that essential developments by PTC carry the great risk of diluting or destroying the original character and standards of Mathcad. 'Developments' in plots, solve blocks, etc. have already shown this.
And yes, there are also some bright spots. I wouldn't want to do without the Ctrl-J feature when creating programs.
And creating and editing matrices is significantly better in Prime than it was in Mathcad. However on the other side, scrolling in large matrices as implemented in Prime is completely unusable 😞
Also the ability to use units in odesolve or to solve simple ODEs symbolically is also very welcome and definitely an improvement.
Not everything about Prime is bad, but....
@Werner_E wrote:
But despite all your efforts and the associated learning effects, the results would probably be quite unsatisfactory.
"Auch du, Werner? Dann fall, Stuart, fall!"
I guess we're going to have to rely on Dave and Martin knowing where The Mathcad Requirements Team live and making them a few offers they can't refuse.
Stuart
@StuartBruff wrote:
I guess we're going to have to rely on Dave and Martin knowing where The Mathcad Requirements Team live and making them a few offers they can't refuse.
By the way, I know where they live, but Dave Martin doesn't. (...And if he does, he shouldn't. He doesn't work for PTC!)
I still think that Games should not be created using a tool like Prime as it lacks far to much features which would be necessary.
But in order to make a constructive contribution to the challenge, I cobbled together at least part of the game.
Prime is placing the ships at random in the grid and the user has to find them by "shooting" at cells.
The history of the shots is recorded in a string via API, so there is no need to create an external file for this purpose.
Unfortunately, I was unable to access a matrix via API (neither for reading nor for changing). I also had problems with normal numbers. I was able to change them, but not read them as numbers – only as strings, which fortunately was sufficient for my purposes. I cannot say whether these problems are due to Prime or my own incompetence. In any case, I would like to see much more detailed and clearer documentation/help on the API, as well as on the scripted controls and supported scripting languages, with significantly more examples.
The cell is selected via two sliders (I really wished they would behave more reliably and consistently). I found no way to be able to directly click a cell as I feel that this sure would be mandatory for a smooth and enjoyable gameplay. After pressing the "Shoot" button the program tells the user if he had success and hit part of a ship, if his shot went into the water or if he had shot at that position already earlier (then the shot is not counted).
As a leftover from testing a cheat mode was left in the sheet, showing the position of all ships:
I don't intend at the moment to implement the second part of the game (user positions the ships and Prime uses an algorithm to find them with as few shots as possible).
But there seems to be quite a lot of literature on hunting algorithms online as well. Maybe someone would like to give it a try...
Prime 11 sheet attached
EDIT: The attached sheet contained an error in the routine that places the ships on the grid. Here is the corrected and slightly expanded version
I was having a look at your excellent worksheet, when a couple of stray thoughts wandered through my brain.
1. You're Austrian? So instead of "Shoot", why not use "Feuer"? I believe "Shoot" is UK (and possibly US) terminology to ensure sailors fire weapons rather than grab extinguishers, but IIRC the German Navy used "Feuer" (relying on its sailors to have better situational awareness?). Perhaps define the command load as a string in any supported language (sadly, Sumerian and Attic Greek aren't), and use that string as input to the control?
2. I wonder if Mathcad Prime can play audio (.wav) files via a component? It would be nice to have something like this -- https://deadsounds.com/flying-artillery-shell-explosion-sound -- play when a player presses "Feuer"/"Shoot"/"Огонь" (but not 𒉈 😢 )
3. Lacking Prime, I can't play with your worksheet, but AFAICT, a relatively easy way to add "random" hits within a cell would be to add an additional character to the each Shot, indicating whether the shot resulted in a hit or not (even if there was ship in that cell).
Stuart
Yes, in German the command would be "Feuer!" or maybe even "Feuer frei!".
And, no, I don't think that Prime could play audio files. MC could and we also could easily create a popup message window or run an arbitrary executable. But Primes "advanced" (? compared to PTC standards?) controls are quite limited. I sorely miss the fact that you cannot assign them to a function. It also looks like only very few attributes are implemented. So in Text boxes amongst others it seems not to be possible to set the font used or styles like italic or bold. I also missed the ability to let the box autosize itself. We also can't set justification via JScript (but we can using the Properties tab). For buttons we can't even set fore- or background color or font size, let alone an image to be displayed as button or at least a nicer 3D look.
But if you like sound you probably like this -> Battleship Online
Do you know that the interims version 11.0.1.0 is available already for a while? I guess you will get another month to play around with the full version if you install it (not sure, though).
If you have the opportunity to play around with the file, you may notice that the “cursor” in the board is only reset to the 0/0 position at the start of a new game (the button also triggers a recalculation) if the option “Run Advanced Control script on worksheet recalculate” is activated in the Prime program options. I have not found a way to force this independently of this setting through the script. However, this may be due to my lack of scripting skills.
If cheat mode is activated when a new game is started, cheat mode is automatically deactivated again, but the button label is mistakenly ON and you have to press the button twice to get back into cheat mode – but that's probably my mistake for not being able to get it right.
In any case, experimenting with the task has once again highlighted the need for significant improvement in the help documentation relating to the API and controls.
I'm not entirely sure what you mean by point 3. Does that refer to your suggestion that a shot at a specific field could, with a certain probability, also land on a neighboring field (in which case it could also trigger a hit there, even though the actual target field is actually water)? Or are you talking about partial hits? In general, I wouldn't know how exactly to deal with such inaccuracies/probabilities in this game. I am also not sure if it would increase the fun playing.
But the actual board game hasn't even been fully implemented yet. To do that, you would need a second playing field on which the human player places their ships, whose positions the computer would then have to guess (as in Alan's last sheet).
In addition, according to the rules referenced by @DaveMartin , when a hit is scored, the type of ship that was hit should also be communicated, and a message should indicate when a ship is completely sunk - "Hit, Cruiser", "Cruiser sunk". This would not be possible with my current approach, as I have no information about which part belongs to which ship after the ships have been placed.
Since, according to the linked rules, the ships are allowed to touch each other, this is often not so easy to determine visually. In my youth (a long time ago), we had agreed otherwise—each ship had to be surrounded by water. However, I can't remember how big our board usually was (played it with paper and pencil) and how many and which ships we had placed there.
In any case, there is plenty of room for improvement, e.g., the variant mentioned in the linked description with multiple shots fired at once.
An interesting challenge would be if the event organizer provided a nice, clean program as a basic framework and the participants only had to submit a function (with specified parameters) that returns the next shooting position.
The organizer could then have these functions compete against each other automatically in a tournament and determine the winner. Just like we used to do in the good old days with "Core War". My algorithm, which I was so proud of at the time, failed miserably. Apparently, I wasn't as good as I thought 😞
In the case of Battleship, the programs wouldn't have to compete against each other specifically, but it would only be necessary to determine which algorithm requires the minimum average number of shots in, say, 100,000 runs.
Oh dear, if only we all had so much time...
"... In addition, according to the rules referenced by @DaveMartin , when a hit is scored, the type of ship that was hit should also be communicated, and a message should indicate when a ship is completely sunk - "Hit, Cruiser", "Cruiser sunk". ..."
The rules that came with my (physical) Battleship game explicitly allow for an option in which the type of ship hit is not communicated. This makes it slightly harder for humans.
"... In the case of Battleship, the programs wouldn't have to compete against each other specifically, but it would only be necessary to determine which algorithm requires the minimum average number of shots in, say, 100,000 runs. ..."
I wrote an article for the December 2020 issue of Mathematics Today, the IMA's in-house magazine (IMA = UK's Institute of Mathematics and Its Applications, not the USA's Institute for Mathematics and Its Applications) that compared three different strategies. I'll attach a pdf of that article here for those who might be interested. Also, the image below shows some histograms of the resulting Monte-Carlo calculations for the three strategies considered, The appendix gives the reasoning behind the theoretical calculation of the mean number of shots for the naïve, totally random strategy. I think it wouldn't be difficult to reproduce the results shown in that article using the full version of Prime. I don't think it's possible to do so using the Express version. ( I actually used Python at the time).
Alan
@AlanStevens wrote:
"... In the case of Battleship, the programs wouldn't have to compete against each other specifically, but it would only be necessary to determine which algorithm requires the minimum average number of shots in, say, 100,000 runs. ..."
I think it wouldn't be difficult to reproduce the results shown in that article using the full version of Prime. I don't think it's possible to do so using the Express version. ( I actually used Python at the time).
What aspects of the results do you think would be difficult to reproduce in Mathcad Express, Alan?
Stuart
@StuartBruff wrote:
What aspects of the results do you think would be difficult to reproduce in Mathcad Express, Alan?
Stuart
Damnation Stuart, stop trying to get me to think! This Challenge is beginning to make my brain hurt!
Ok. The naïve random random version can be done quite simply. In fact I've just done it - see attached file and the resulting histogram below.
For the other strategies though, for each MC trial one has to search the positions around each hit and or consider two sublattices (think of the grid as alternating coloured squares - like a chess board). This is too much for my poor brain to take! However, I would be delighted to see you succeed in doing it.
Alan
I tried that thinking lark once. Made my head hurt. I don't think I'll be doing it again.
In the meantime, now that I've finished fixing the car, I'll shamelessly steal your board initialisation routine (assuming there is one!) to help me expand upon my "idea" for Werner's question (re random hit tracking).
Stuart
@StuartBruff wrote:
I tried that thinking lark once. Made my head hurt. I don't think I'll be doing it again.
In the meantime, now that I've finished fixing the car, I'll shamelessly steal your board initialisation routine (assuming there is one!) to help me expand upon my "idea" for Werner's question (re random hit tracking).
Arrgghh! There's no Express-friendly ship placement function to steal! How's an honest thief supposed to make a living if people don't have anything to steal???
I guess I'll have to summon up the resolve, dedication, and whatever (desperation?) to convert Werner's Prime method to Express.
Sigh.
Stuart
@AlanStevens wrote:
...okay I guess the 54 shots I got was really much better than average. So if I play again I'll get much worse. Probably.
Actually we never used a physical set for playing the game, just checkered paper and pen. Not sure if there are "official" rules. While surfing the net I found a lot of different versions and rules. Some would use ships of the size 1x1, another large ones like 5x2 (on a larger grid). Often a rule is that every ship must be surrounded by water (that's what we usually agreed upon when playing it). Announcing which ship was hit or sunk may make it easier for human players but I guess it makes it more difficult for an algorithm to deal with that information.
Thanks for the pdf you attached, looks interesting at first glance. I was also looking around when I first read about this challenge and was surprised how much could be found about strategy in placing ships or choosing the coordinates to try.
This one -> Coding an Intelligent Battleship Agent <- looked promising but I didn't go any further with it, though..
@Werner_E wrote:
Yes, in German the command would be "Feuer!" or maybe even "Feuer frei!".
And, no, I don't think that Prime could play audio files. MC could and we also could easily create a popup message window or run an arbitrary executable. But Primes "advanced" (? compared to PTC standards?) controls are quite limited. I sorely miss the fact that you cannot assign them to a function. It also looks like only very few attributes are implemented. So in Text boxes amongst others it seems not to be possible to set the font used or styles like italic or bold. I also missed the ability to let the box autosize itself. We also can't set justification via JScript (but we can using the Properties tab). For buttons we can't even set fore- or background color or font size, let alone an image to be displayed as button or at least a nicer 3D look.
Sounds like a flurry of Mathcad Enhancement Proposals are needed!
@Werner_E wrote:
Do you know that the interims version 11.0.1.0 is available already for a while? I guess you will get another month to play around with the full version if you install it (not sure, though).
I did notice, thanks, but I don't think the upgrade allows Express users to get an extra 30-days. I'll have to recheck.
@Werner_E wrote:
In any case, experimenting with the task has once again highlighted the need for significant improvement in the help documentation relating to the API and controls.
Yes, and I haven't noticed any response to getting an advanced control to set array values.
I recently added another item to my very long "Play With" list. I found an interesting piece of modern Fortran code to convert to Mathcad. I notice from the Mathcad Help that Fortran is supported if you put the compiled code in a C/C++ wrapper. Unfortunately, the Help makes reference to the Compaq Fortran Compiler, whereas we've now got the 2025 Intel Fortran Compiler in Visual Studio 2022. There's still a decent amount of useful Fortran code out there and it would be nice to write a Fortran DLL that integrates into Mathcad -- but I've got far too much on my plate to spend any time on it at the moment.
@Werner_E wrote:
I'm not entirely sure what you mean by point 3. Does that refer to your suggestion that a shot at a specific field could, with a certain probability, also land on a neighboring field (in which case it could also trigger a hit there, even though the actual target field is actually water)? Or are you talking about partial hits? In general, I wouldn't know how exactly to deal with such inaccuracies/probabilities in this game. I am also not sure if it would increase the fun playing.
Either option; a) miss but the shot remains within the chosen cell, or b) lands in an adjacent cell.
I'll have a further look at your worksheet and see if I can suggest a means. I have an idea .... 😈
Although, it might require some detailed modification.
@Werner_E wrote:
But the actual board game hasn't even been fully implemented yet. To do that, you would need a second playing field on which the human player places their ships, whose positions the computer would then have to guess (as in Alan's last sheet).
In addition, according to the rules referenced by @DaveMartin , when a hit is scored, the type of ship that was hit should also be communicated, and a message should indicate when a ship is completely sunk - "Hit, Cruiser", "Cruiser sunk". This would not be possible with my current approach, as I have no information about which part belongs to which ship after the ships have been placed.
That's where my idea might help. But you've probably had ideas of your own; ones that might actually work!
@Werner_E wrote:
In the case of Battleship, the programs wouldn't have to compete against each other specifically, but it would only be necessary to determine which algorithm requires the minimum average number of shots in, say, 100,000 runs.
That, is what automation is for!
@Werner_E wrote:
In the case of Battleship, the programs wouldn't have to compete against each other specifically, but it would only be necessary to determine which algorithm requires the minimum average number of shots in, say, 100,000 runs.
Oh dear, if only we all had so much time...
Core Wars! Wow, that's a blast from the past. The most enjoyable game I played was back when a friend and I were playing with a new system at work.
Our engineering department had acquired a new minicomputer, but there was a problem getting a peripheral device to play nicely with the computer. The powers-that-be decided to task my friend Brian and I with fixing it, despite neither of us being software engineers. I was busy designing radar tracking algorithms, and Brian was a hardware design engineer; at least, he had a lot of experience dealing with real-time systems, but I couldn't understand why they asked me. I was less than a year out of university, a physicist, and only dabbled in software.
After a short while, we managed to crack the problem, but as the new computer was still in its workup phase and not released for official business, we decided to experiment with the OS. It wasn't long before it devolved into Core Wars Lite. Eventually, the computer system manager noticed that everyone else involved in the workup was sitting around twiddling their thumbs. So, he enquired and determined that all the other users were unable to survive in the hostile OS environment we'd created. He promptly used his admin privileges to kick us off the system. It was lunch time anyway, so off we went to the canteen.
After lunch, the computer system manager came back to find Brian and I sitting at two terminals, innocently typing away, whilst the others were cowering in a corner, chittering away, wearing expressions of existential terror. I don't know why, we were behaving ourselves.
So, the manager glowers at us both, stalks to his admin terminal. And finds he can't log in.
How he could have been so naive as to think he could have revoked our access, I don't know. Neither did he apparently understand that there would be ... repercussions. 😈
In the meantime, I have to complete today's main task, which is fixing my car. There was a time when I enjoyed the challenge of working out why a car wouldn't start - again! I'd forgotten why I normally employ minions to fix mechanical things these days.
Stuart
@StuartBruff wrote:
@Werner_E wrote:
Do you know that the interims version 11.0.1.0 is available already for a while? I guess you will get another month to play around with the full version if you install it (not sure, though).
I did notice, thanks, but I don't think the upgrade allows Express users to get an extra 30-days. I'll have to recheck.
So far, I haven't even received an email with the download link.
Well if you still have the old email with the download link, that one will...still work. The link is the same but the .exe downloaded from the link is different.
(Don't tell too many people that, but I guess I'm also promoting this community challenge to the whole world, so oh well...)
That worked, thanks. I now have Mathcad Prime 11.0.1.0 installed.
Unfortunately, the licence server is smart enough to know I've already reached my limit on Mathcad Prime 11.x.x.x licences.
Stuart
I wasn't thinking about using the automation interface, just a simple function with the function which plays the game as argument (or a list of such functions) and for loop where ships are placed and then the algorithm(s) called and counted how many shots they need.
Not much user interaction or outputs to see other than the statistical data.
The story you tell does not sound like Core War light but rather like some kind of war you and Brian against the rest 😉
