-
Notifications
You must be signed in to change notification settings - Fork 0
/
tanks.py
325 lines (274 loc) · 8.45 KB
/
tanks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 18 19:18:02 2018
@author: John Zarcone
"""
import numpy as np
import matplotlib.pyplot as plt
#collabed with Kristina E, Kat A, Haitiana A, Dilan D
tank1Color = 'b'
tank2Color = 'r'
obstacleColor = 'k'
##### functions you need to implement #####
def trajectory (x0,y0,v,theta,g = 9.8, npts = 1000):
"""
finds the x-y trajectory of a projectile
parameters
----------
x0 : float
initial x - position
y0 : float
initial y - position, must be >0
initial velocity
theta : float
initial angle (in degrees)
g : float (default 9.8)
acceleration due to gravity
npts : int
number of points in the sample
returns
-------
(x,y) : tuple of np.array of floats
trajectory of the projectile vs time
notes
-----
trajectory is sampled with npts time points between 0 and
the time when the y = 0 (regardless of y0)
y(t) = y0 + vsin(theta) t - 0.5 g t^2
0.5g t^2 - vsin(theta) t - y0 = 0
t_final = v/g sin(theta) + sqrt((v/g)^2 sin^2(theta) + 2 y0/g)
"""
theta = np.deg2rad(theta)
vx = np.cos(theta)*v
vy = np.sin(theta)*v
t_final = ((v/g)*np.sin(theta)+np.sqrt((((v*np.sin(theta))/g)**2)+(2*(y0/g))))
t = np.linspace(0, t_final)
x = x0+(vx*t)
y = y0+(vy*t)-(.5*g*(t**2))
return(x,y)
def firstInBox (x,y,box):
"""
finds first index of x,y inside box
paramaters
----------
x,y : np array type
positions to check
box : tuple
(left,right,bottom,top)
returns
-------
int
the lowest j such that
x[j] is in [left,right] and
y[j] is in [bottom,top]
-1 if the line x,y does not go through the box
"""
inbox = False
for j in range(0, len(x)):
if x[j]>= box[0] and x[j]<=box[1] and y[j] >= box[2] and y[j] <= box[3]:
inbox = True
return j
break
if inbox == False:
return -1
def tankShot (targetBox, obstacleBox, x0, y0, v, theta, g = 9.8):
"""
executes one tank shot
parameters
----------
targetBox : tuple
(left,right,bottom,top) location of the target
obstacleBox : tuple
(left,right,bottom,top) location of the central obstacle
x0,y0 :floats
origin of the shot
v : float
velocity of the shot
theta : float
angle of the shot
g : float
accel due to gravity (default 9.8)
returns
--------
int
code: 0 = miss, 1 = hit
hit if trajectory intersects target box before intersecting
obstacle box
draws the truncated trajectory in current plot window
"""
[x,y]= trajectory(x0,y0,v,theta)
if firstInBox(x, y, obstacleBox) != -1:
x2, y2 = endTrajectoryAtIntersection(x, y, targetBox)
plt.plot(x2, y2)
return 0
else:
if firstInBox(x, y, targetBox) >= 0:
x2, y2 = endTrajectoryAtIntersection(x, y, targetBox)
plt.plot(x2, y2)
return 1
else:
return 0
def drawBoard (tank1box, tank2box, obstacleBox, playerNum):
"""
draws the game board, pre-shot
parameters
----------
tank1box : tuple
(left,right,bottom,top) location of player1's tank
tank2box : tuple
(left,right,bottom,top) location of player1's tank
obstacleBox : tuple
(left,right,bottom,top) location of the central obstacle
playerNum : int
1 or 2 -- who's turn it is to shoot
"""
plt.clf()
drawBox(tank1box, 'c')
drawBox(tank2box, 'm')
drawBox(obstacleBox, 'r')
plt.xlim(0,100)
plt.ylim(0,100)
showWindow() #this makes the figure window show up
def oneTurn (tank1box, tank2box, obstacleBox, playerNum, g = 9.8):
"""
parameters
----------
tank1box : tuple
(left,right,bottom,top) location of player1's tank
tank2box : tuple
(left,right,bottom,top) location of player1's tank
obstacleBox : tuple
(left,right,bottom,top) location of the central obstacle
playerNum : int
1 or 2 -- who's turn it is to shoot
g : float
accel due to gravity (default 9.8)
returns
-------
int
code 0 = miss, 1 or 2 -- that player won
clears figure
draws tanks and obstacles as boxes
prompts player for velocity and angle
displays trajectory (shot originates from center of tank)
returns 0 for miss, 1 or 2 for victory
"""
drawBoard(tank1box, tank2box, obstacleBox, playerNum)
angle = getNumberInput("What angle do you want to shoot from in degrees?")
velocity = getNumberInput("What velocity do you want to shoot at in meters/second?")
if playerNum == 1:
origin = tank1box
target = tank2box
if playerNum == 2:
origin = tank2box
target = tank1box
x0= (origin[0]+origin[1])/2
y0= (origin[2]+origin[3])/2
outcome = tankShot(target, obstacleBox, x0, y0, v, theta)
if outcome ==1:
return playerNum
else:
return 0
def playGame(tank1box, tank2box, obstacleBox, g = 9.8):
"""
parameters
----------
tank1box : tuple
(left,right,bottom,top) location of player1's tank
tank2box : tuple
(left,right,bottom,top) location of player1's tank
obstacleBox : tuple
(left,right,bottom,top) location of the central obstacle
playerNum : int
1 or 2 -- who's turn it is to shoot
g : float
accel due to gravity (default 9.8)
"""
playerNum = 1
while True:
turn = oneTurn(tank1box, tank2box, obstacleBox, playerNum)
if turn == 0:
print("Player ", playerNum, "you missed. Other players turn!")
elif turn == 1:
print("Player ", playerNum, "you won the game. Congrats!")
elif turn == 2:
print("Player ", playerNum, "you won the game. Congrats!")
x = input("Please continue to play!")
##### functions provided to you #####
def getNumberInput (prompt, validRange = [-np.Inf, np.Inf]):
"""displays prompt and converts user input to a number
in case of non-numeric input, re-prompts user for numeric input
Parameters
----------
prompt : str
prompt displayed to user
validRange : list, optional
two element list of form [min, max]
value entered must be in range [min, max] inclusive
Returns
-------
float
number entered by user
"""
while True:
try:
num = float(input(prompt))
except Exception:
print ("Please enter a number")
else:
if (num >= validRange[0] and num <= validRange[1]):
return num
else:
print ("Please enter a value in the range [", validRange[0], ",", validRange[1], ")") #Python 3 sytanx
return num
def showWindow():
"""
shows the window -- call at end of drawBoard and tankShot
"""
plt.draw()
plt.pause(0.001)
plt.show()
def drawBox(box, color):
"""
draws a filled box in the current axis
parameters
----------
box : tuple
(left,right,bottom,top) - extents of the box
color : str
color to fill the box with, e.g. 'b'
"""
x = (box[0], box[0], box[1], box[1])
y = (box[2], box[3], box[3], box[2])
ax = plt.gca()
ax.fill(x,y, c = color)
def endTrajectoryAtIntersection (x,y,box):
"""
portion of trajectory prior to first intersection with box
paramaters
----------
x,y : np array type
position to check
box : tuple
(left,right,bottom,top)
returns
----------
(x,y) : tuple of np.array of floats
equal to inputs if (x,y) does not intersect box
otherwise returns the initial portion of the trajectory
up until the point of intersection with the box
"""
i = firstInBox(x,y,box)
if (i < 0):
return (x,y)
return (x[0:i],y[0:i])
##### fmain -- edit box locations for new games #####
def main():
tank1box = [10,15,0,5]
tank2box = [90,95,0,5]
obstacleBox = [40,60,0,50]
playGame(tank1box, tank2box, obstacleBox)
#don't edit the lines below;
if __name__== "__main__":
main()