4

I am designing a tank game in Mathematica for my class and currently I have a tank that can drive along a curve and shoot a point at a set angle, but I want to get all of this into some sort of pup up window or dialog notebook so that when I run the program it will make a window in it where i can interact with it with the arrow keys. A simple version of my code is below.

(*This function finds all of the points that the shot should travel \
along while it is in the air of its shot*)
Clear[shoot]; 
shoot[pt1_, y1_] := Module[{above = True, y = y1, pt = pt1, pts = {}},
While[f[pt[[1]]] <= pt[[2]], pt[[1]] = Round[pt[[1]] + 0.01, 0.01];
pt[[2]] = Round[(pt[[2]] + (0.01 - ((y - y1)*0.0001))), 0.0001];
AppendTo[pts, pt]; y++];
Return[pts];
]

f[x_] := N@Sin[x];

run[] := DynamicModule[{pt = {0, 0}, pt1 = {0, 0}, pts = {}},
EventHandler[
(*first i show the graph of the function defined previously*)
Show[Graphics[{{Blue, Dynamic[Disk[pt1, .01]]}, {Red, 
   Dynamic[Circle[pt, .1]]}
  }, PlotRange -> 1, Axes -> True], Plot[f[x], {x, -10, 10}]],
(*here you can move the circle and point that will be shot right \
with the right arrow*)
{"RightArrowKeyDown" :> 
 If[pt[[1]] < .9, pt = pt + {.05, 0}; pt1 = pt1 + {.05, 0};]},
(*left arrow*)
{"LeftArrowKeyDown" :> 
 If[pt[[1]] > -.9, pt = pt - {.05, 0}; pt1 = pt1 - {.05, 0};]},
(*up arrow*)
{"UpArrowKeyDown" :> 
 If[pt[[2]] < .9, pt = pt + {0, .05}; pt1 = pt1 + {0, .05};]},
(*down arrow*)
{"DownArrowKeyDown" :> 
 If[pt[[2]] > -.9, pt = pt - {0, .05}; pt1 = pt1 - {0, .05};]},
(*when you press space the point in the middle of the circle is \
shot and stops when it hits the line*)
(*the point can not be shot from below the curve*)
{{"KeyDown", " "} :> (pts = shoot[pt1, pt1[[2]]]; 
  Do[pt1 = pts[[i]]; FinishDynamic[]; 
   If[i == Length[pts], pt1 = pt], {i, 1, Length[pts]}];)}
]
]

To run the code just evaluate it all and type run[] I dont think my code needs to be adjusted but I do not know how to show it in a window.

  • 1
    Very neat! I would suggest, however, that you try to minimize your code to the simplest example possible to demonstrate what you are after. This will increase the chances of someone helping, as your code now is a little intimidating. You can then generalize the solution from the simple example and apply it to your larger code base. – ktm Apr 10 '17 at 21:29
  • @user6014 I changed it so that it has one of my first increments of the code that is similar and much simpler. Thank you. – steven gaiko Apr 10 '17 at 21:38

1 Answers1

3

What if you did something like this:

game = DynamicModule[(*the dynamic module code you had in your 
  original post, omitting it for the sake of space*)];
run[] := CreateDocument[game, WindowSize -> All, 
  WindowElements -> None, WindowTitle -> "Crazy Tank Battle Game"]

There are other options you can use to customer the created notebook as well.

ktm
  • 4,242
  • 20
  • 28