├── README.md ├── LICENSE └── starwars_III.py /README.md: -------------------------------------------------------------------------------- 1 | Star-Wars-III 2 | ============= 3 | 4 | A remake of the trench sequence of star wars (level III), a vintage arcade game. A fun coding weekend at PESIT with the juniors. 5 | 6 | The code runs perfectly fine in the CodeSkulptor development environment. The IDE can be found here. (http://www.codeskulptor.org/) 7 | 8 | The rules go like on similar grounds to the level 3 star wars sequence game. 9 | 10 | The Death Star can be destroyed about once every three attempts, but the code can be edited for a wishful number of attempt. Shrink the dimensions of your X-Wing, or reduce your velocity if you find it too tough. 11 | 12 | Tip 1: remember that X-Wings are wider than they are tall. 13 | Tip 2: don't forget to fire your proton torpedoes once your distance display reads zero. 14 | 15 | Play & relive the vintage arcade games era. 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /starwars_III.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | import simplegui 4 | import time 5 | 6 | VERSION = "v1.5" 7 | 8 | CANVAS_WIDTH = 800 9 | CANVAS_HEIGHT = 600 10 | TRENCH_LENGTH_M = 3500 11 | TRENCH_WIDTH_M = 10 12 | TRENCH_HEIGHT_M = 10 13 | TRENCH_WALL_INTERVAL_M = 20 14 | TRENCH_COLOUR = "#ddd" 15 | EXHAUST_PORT_POSITION_M = TRENCH_LENGTH_M - 100 16 | EXHAUST_PORT_WIDTH_M = TRENCH_WIDTH_M / 3.0 17 | PROTON_TORPEDO_RANGE_M = 200 18 | PROTON_TORPEDO_RADIUS_M = 0.3 19 | PROTON_TORPEDO_SPAN_M = 0.7 20 | LAUNCH_POSITION_M = EXHAUST_PORT_POSITION_M - PROTON_TORPEDO_RANGE_M 21 | DISTANCE_COLOUR = "Red" 22 | DEATH_STAR_RADIUS = CANVAS_HEIGHT * 0.4 23 | DEATH_STAR_COLOUR = "#aaa" 24 | LINE_WIDTH = 2 25 | 26 | MODE_INTRO = 0 27 | MODE_GAME = 1 28 | MODE_VICTORY = 2 29 | 30 | SHIP_WIDTH_M = 1.6 31 | SHIP_HEIGHT_M = 0.8 32 | 33 | NEAR_PLANE_M = 0.1 34 | FAR_PLANE_M = 180.0 35 | SCALE_WIDTH = CANVAS_WIDTH / 2 36 | SCALE_HEIGHT = CANVAS_HEIGHT / 2 37 | 38 | FORWARD_VELOCITY_MS = 60.0 39 | PROTON_TORPEDO_VELOCITY_MS = FORWARD_VELOCITY_MS * 1.1 40 | VELOCITY_MAX_MS = 15.0 41 | VELOCITY_DAMPEN = 0.7 42 | ACCELERATION_MSS = 100.0 43 | 44 | TORPEDO_COLOUR = "Red" 45 | EXHAUST_PORT_COLOUR = "Red" 46 | INTRO_TEXT_COLOUR = "Yellow" 47 | WARNING_TEXT_COLOUR = "Red" 48 | PARTICLE_COLOUR = "White" 49 | FONT_STYLE = "sans-serif" 50 | 51 | BARRIER_COLOURS = ( ( 255, 0, 0 ), ( 255, 192, 0 ), ( 0, 255, 0 ), ( 255, 255, 0 ), ( 0, 255, 255 ), ( 255, 0, 255 ) ) 52 | 53 | BLOCK_VERTEX = ( ( 0, 1 ), ( 1, 2 ), ( 2, 3 ), ( 3, 0 ), ( 0, 4 ), ( 1, 5 ), ( 2, 6 ), ( 3, 7 ), ( 4, 5 ), ( 5, 6 ), ( 6, 7 ), ( 7, 4 ), ( 0, 2 ), ( 1, 3 ) ) 54 | 55 | HEX_DIGITS = ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' ) 56 | 57 | # Ship Variables 58 | pos = [] 59 | vel = [] 60 | acc = [] 61 | 62 | # Proton Torpedo Variables 63 | pt_pos = [] 64 | pt_launch_position = 0 65 | 66 | # Exhaust Port in Range 67 | reached_launch_position = False 68 | 69 | # Trench Barriers 70 | barriers = [] 71 | current_barrier_index = 0 72 | 73 | # Message 74 | message = "" 75 | message_delay = 0 76 | message_tick = 0 77 | 78 | # Stars 79 | stars = [] 80 | 81 | # Victory 82 | explosion_countdown = 0 83 | particles = [] 84 | 85 | # Game State 86 | game_mode = MODE_INTRO 87 | dead = False 88 | violent_death = True 89 | 90 | # Actual FPS 91 | last_time = 0 92 | fps = 60 93 | 94 | # Return the centre point of the canvas 95 | def get_canvas_centre(): 96 | return ( CANVAS_WIDTH // 2, CANVAS_HEIGHT // 2 ) 97 | 98 | # Convert a number from 0 to 255 to a pair of hex digits - used in calculating RGB colour values 99 | def hex( n ): 100 | n = min( int( n ), 255 ) 101 | d1 = HEX_DIGITS[ n // 16 ] 102 | d2 = HEX_DIGITS[ n % 16 ] 103 | return d1 + d2 104 | 105 | # Creates an array of stars randomly scattered on the canvas 106 | def create_stars(): 107 | while len( stars ) < 300: 108 | x = random.randrange( CANVAS_WIDTH ) 109 | y = random.randrange( CANVAS_HEIGHT ) 110 | stars.append( ( x, y ) ) 111 | 112 | # Creates all of the barriers that appear in the game. Each Barrier is represented by three elements: 113 | # Start Position - the distance along the trench that the barrier starts 114 | # Length - the length of the barrier 115 | # Blocks - an array of 9 ints, either 1 or 0, that indicate which blocks in a 3x3 square appear in the barrier. 116 | # The Barriers are placed in a list which is sequenced by the Start Position of the Barriers. This allows 117 | # the rendering and collision code to consider only the barriers immediately surrounding the ship. 118 | def create_barriers(): 119 | global barriers 120 | barriers = [] 121 | 122 | # Determine Start Position and Last Position 123 | s = 150.0 124 | limit = LAUNCH_POSITION_M - 150 125 | while s < limit: 126 | # Create a totally solid barrier 127 | blocks = [] 128 | for i in range( 0, 9 ): 129 | blocks.append( 1 ) 130 | 131 | # Punch a number of empty blocks in the barrier, based on how close to the end of the trench the barrier is. 132 | empty_blocks = 1.0 - ( s / limit ) 133 | empty_blocks = int( ( empty_blocks * 8 ) ) + 2 134 | for i in range( 0, empty_blocks ): 135 | blocks[ random.randrange( 9 ) ] = 0 136 | 137 | # Calculate a random length 138 | l = random.randrange( 5 ) + 5 139 | barriers.append( ( s, l, blocks ) ) 140 | s += l 141 | s += 40 + random.randrange( 30 ) 142 | 143 | # Initialise all game variables to prepare for a new game 144 | def init_game(): 145 | global game_mode, pos, vel, acc, pt_pos, pt_launch_position, reached_launch_position, current_barrier_index, dead, explosion_countdown 146 | game_mode = MODE_GAME 147 | pos = [ 0, 0, 0 ] 148 | vel = [ 0, 0, FORWARD_VELOCITY_MS ] 149 | acc = [ 0, 0, 0 ] 150 | pt_pos = [] 151 | pt_launch_position = -1 152 | reached_launch_position = False 153 | dead = False 154 | current_barrier_index = 0 155 | explosion_countdown = 0 156 | create_barriers() 157 | set_message( "Use the Force" ) 158 | 159 | # Calculates the distance remaining until the ship reaches the torpoedo launch position 160 | def get_distance_to_launch_position(): 161 | return LAUNCH_POSITION_M - pos[ 2 ] 162 | 163 | # Indicates whether the ship is 'close' to the launch position. 164 | def is_close_to_launch_position(): 165 | return math.fabs( get_distance_to_launch_position() ) < 100.0 166 | 167 | # Fire the Proton Torpedoes, if they haven't already been launched. 168 | # They are initially positioned slightly under the ship. 169 | def launch_proton_torpedoes(): 170 | global pt_launch_position 171 | 172 | if pt_launch_position < 0 and is_close_to_launch_position(): 173 | pt_pos.append( [ pos[ 0 ] - PROTON_TORPEDO_SPAN_M, pos[ 1 ] + 1, pos[ 2 ] ] ) 174 | pt_pos.append( [ pos[ 0 ] + PROTON_TORPEDO_SPAN_M, pos[ 1 ] + 1, pos[ 2 ] ] ) 175 | pt_launch_position = pos[ 2 ] 176 | 177 | # Sets the current message. The message appears for 3 seconds. 178 | def set_message( new_message ): 179 | global message, message_delay, message_tick 180 | message = new_message 181 | message_delay = 3 182 | message_tick = 0 183 | 184 | # Projects a 3d point into a 2d canvas coordinate. The 3d coordinates are based on +x -> right, +y -> down +z -> away. 185 | # The origin of the 3d coordinate system is the ship's initial position in the middle of the start of the trench. 186 | def project( point ): 187 | distance = point[ 2 ] - pos[ 2 ] 188 | if distance <= NEAR_PLANE_M: 189 | distance = NEAR_PLANE_M 190 | x = ( point[ 0 ] - pos[ 0 ] ) / ( distance + NEAR_PLANE_M ) 191 | y = ( point[ 1 ] - pos[ 1 ] ) / ( distance + NEAR_PLANE_M ) 192 | x *= SCALE_WIDTH 193 | y *= SCALE_HEIGHT 194 | x += ( CANVAS_WIDTH // 2 ) 195 | y += ( CANVAS_HEIGHT // 2 ) 196 | return ( x, y ) 197 | 198 | # Displays the Death sequence. If the flashing colours are enabled, then a red rectangle is drawn onto the screen every other frame. 199 | def render_death( canvas ): 200 | global message_tick 201 | if dead: 202 | if violent_death and ( message_tick % 2 == 0 ) : 203 | canvas.draw_polygon( ( ( 0, 0 ), ( CANVAS_WIDTH, 0 ), ( CANVAS_WIDTH, CANVAS_HEIGHT ), ( 0, CANVAS_HEIGHT ) ), 1, "Red", "Red" ) 204 | message_tick += 1 205 | 206 | # Draws the trench. Firstly, four lines are drawn from the player's z position towards the end of the trench. 207 | # Secondly, a rectangle is drawn at the end of the trench. 208 | # Thirdly, the lines along the wall are drawn. 209 | def render_trench( canvas ): 210 | tw = TRENCH_WIDTH_M // 2 211 | th = TRENCH_HEIGHT_M // 2 212 | trench = ( [ -tw, -th ], [ tw, -th ], [ tw, th ], [ -tw, th ] ) 213 | trench_p = [] 214 | for t in trench: 215 | near = list( t ) 216 | near.append( pos[ 2 ] ) 217 | far = list( t ) 218 | far.append( TRENCH_LENGTH_M ) 219 | near_p = project( near ) 220 | far_p = project( far ) 221 | canvas.draw_line( near_p, far_p, LINE_WIDTH, TRENCH_COLOUR ) 222 | trench_p.append( far_p ) 223 | 224 | # Draw far wall 225 | trench_p.append( trench_p[ 0 ] ) 226 | canvas.draw_polyline( trench_p, LINE_WIDTH, TRENCH_COLOUR ) 227 | 228 | # Draw vertical walls 229 | distance = ( int( pos[ 2 ] + TRENCH_WALL_INTERVAL_M ) // TRENCH_WALL_INTERVAL_M ) * TRENCH_WALL_INTERVAL_M 230 | limit = min( pos[ 2 ] + FAR_PLANE_M, TRENCH_LENGTH_M ) 231 | while distance < limit: 232 | for side in [ -1, 1 ]: 233 | p1 = project( ( side * tw, -th, distance ) ) 234 | p2 = project( ( side * tw, th, distance ) ) 235 | canvas.draw_line( p1, p2, LINE_WIDTH, TRENCH_COLOUR ) 236 | distance += TRENCH_WALL_INTERVAL_M 237 | 238 | # Draws a single barrier. 239 | def render_barrier( canvas, barrier ): 240 | n = barrier[ 0 ] # Barrier Start Position 241 | f = n + barrier[ 1 ] # Barrier End Position 242 | m = barrier[ 2 ] # Barrier Block Array 243 | w = TRENCH_WIDTH_M / 3.0 # Block Width 244 | h = TRENCH_HEIGHT_M / 3.0 # Block Height 245 | hw = w / 2.0 # Block Half Width 246 | hh = h / 2.0 # Block Half Height 247 | 248 | # Calculate the colour of the blocks, based on base colour and distance. 249 | # The barrier's base colour is taken from its start position. 250 | distance = 1.0 - 0.9 * ( n - pos[ 2 ] ) / FAR_PLANE_M 251 | base_colour = BARRIER_COLOURS[ n % len( BARRIER_COLOURS ) ] 252 | colour = "#" 253 | for component in range( 0, 3 ): 254 | colour += hex( base_colour[ component ] * distance ) 255 | 256 | i = 0 # Block Index ( 0 to 8 ) 257 | for y in range( -1, 2 ): 258 | for x in range( -1, 2 ): 259 | if m[ i ] == 1: # Test if Block is present 260 | px = x * w # Coordinates at the centre of the block 261 | py = y * h 262 | cube = ( # Define a tuple containing the coordinates for this cube. They are indexed by BLOCK_VERTEX. 263 | ( px - hw, py - hh, n ), 264 | ( px + hw, py - hh, n ), 265 | ( px + hw, py + hh, n ), 266 | ( px - hw, py + hh, n ), 267 | ( px - hw, py - hh, f ), 268 | ( px + hw, py - hh, f ), 269 | ( px + hw, py + hh, f ), 270 | ( px - hw, py + hh, f ) 271 | ) 272 | 273 | # Project the 3d coordinates into 2d canvas coordinates 274 | cube_p = [] 275 | for p in cube: 276 | cube_p.append( project( p ) ) 277 | 278 | # Draw the lines 279 | for vi in BLOCK_VERTEX: 280 | canvas.draw_line( cube_p[ vi[ 0 ] ], cube_p[ vi[ 1 ] ], LINE_WIDTH, colour ) 281 | i += 1 282 | 283 | # Draws all of the visible barriers. The game remembers the first visible barrier (current_barrier_index), 284 | # so that each frame it doesn't need to go through the entire list of barriers to get the first that is visible. 285 | # The visible barriers are always inserted at the front of their own list, which ensures that they are drawn back to front. 286 | def render_barriers( canvas ): 287 | global current_barrier_index 288 | visible_barriers = [] 289 | 290 | index = current_barrier_index 291 | while index < len( barriers ): 292 | barrier = barriers[ index ] 293 | index += 1 294 | visible = ( barrier[ 0 ] + barrier[ 1 ] - pos[ 2 ] ) > NEAR_PLANE_M 295 | visible = visible and ( barrier[ 0 ] - pos[ 2 ] < FAR_PLANE_M ) 296 | if visible: 297 | visible_barriers.insert( 0, barrier ) 298 | elif pos[ 2 ] > barrier[ 0 ]: 299 | current_barrier_index = index 300 | else: 301 | break 302 | 303 | for barrier in visible_barriers: 304 | render_barrier( canvas, barrier ) 305 | 306 | def render_exhaust_port( canvas ): 307 | if reached_launch_position: 308 | y = TRENCH_HEIGHT_M / 2 309 | z = EXHAUST_PORT_POSITION_M 310 | w = EXHAUST_PORT_WIDTH_M 311 | hw = w / 2 312 | hole = ( ( -hw, y, z - hw ), ( hw, y, z - hw ), ( hw, y, z + hw ), ( -hw, y, z + hw ) ) 313 | coords = [] 314 | for p in hole: 315 | coords.append( project( p ) ) 316 | coords.append( coords[ 0 ] ) 317 | canvas.draw_polyline( coords, LINE_WIDTH, EXHAUST_PORT_COLOUR ) 318 | 319 | canvas.draw_line( project( ( -w, y, z ) ), project( ( -hw, y, z ) ), LINE_WIDTH, EXHAUST_PORT_COLOUR ) 320 | canvas.draw_line( project( ( w, y, z ) ), project( ( hw, y, z ) ), LINE_WIDTH, EXHAUST_PORT_COLOUR ) 321 | canvas.draw_line( project( ( 0, y, z - w ) ), project( ( 0, y, z - hw ) ), LINE_WIDTH, EXHAUST_PORT_COLOUR ) 322 | canvas.draw_line( project( ( 0, y, z + w ) ), project( ( 0, y, z + hw ) ), LINE_WIDTH, EXHAUST_PORT_COLOUR ) 323 | 324 | def render_torpedo( canvas, pos ): 325 | centre = project( pos ) 326 | edge = project( [ pos[ 0 ] - PROTON_TORPEDO_RADIUS_M, pos[ 1 ], pos[ 2 ] ] ) 327 | radius = centre[ 0 ] - edge[ 0 ] 328 | canvas.draw_circle( centre, radius, LINE_WIDTH, TORPEDO_COLOUR ) 329 | 330 | def render_torpedoes( canvas ): 331 | if len( pt_pos ) > 0: 332 | for p in pt_pos: 333 | render_torpedo( canvas, p ) 334 | 335 | def render_distance( canvas ): 336 | distance = int( get_distance_to_launch_position() ) 337 | if distance > 0: 338 | distance_str = str( distance ) 339 | while len( distance_str ) < 5: 340 | distance_str = "0" + distance_str 341 | distance_str += "m" 342 | draw_text_centre( canvas, distance_str, CANVAS_HEIGHT - 4, 29, DISTANCE_COLOUR ) 343 | 344 | def render_message( canvas ): 345 | global message_delay 346 | if ( message_delay > 0 ): 347 | y = CANVAS_HEIGHT // 2 + 90 348 | for line in message.split( "\n" ): 349 | draw_text_centre( canvas, line, y, 35, "White" ) 350 | y += 45 351 | 352 | def move_ship(): 353 | global pos, vel, acc, pt_launch_position 354 | 355 | # Pull up at the end of the Trench 356 | if pos[ 2 ] > EXHAUST_PORT_POSITION_M: 357 | acc[ 1 ] = -ACCELERATION_MSS 358 | if pt_launch_position < 0: 359 | set_message( "You forgot to fire your torpedoes" ) 360 | pt_launch_position = 0 361 | 362 | # Slow down when poised to launch torpedo 363 | factor = float( fps ) 364 | if pt_launch_position < 0 and is_close_to_launch_position(): 365 | factor *= 4 366 | 367 | for i in range( 0, 3 ): 368 | pos[ i ] += vel[ i ] / factor 369 | if acc[ i ] != 0: 370 | vel[ i ] += acc[ i ] / factor 371 | if vel[ i ] < -VELOCITY_MAX_MS: 372 | vel[ i ] = -VELOCITY_MAX_MS 373 | elif vel[ i ] > VELOCITY_MAX_MS: 374 | vel[ i ] = VELOCITY_MAX_MS 375 | elif i < 2: 376 | vel[ i ] *= VELOCITY_DAMPEN 377 | 378 | def move_torpedoes(): 379 | global pt_pos, explosion_countdown 380 | if len( pt_pos ) > 0: 381 | hit = False 382 | bullseye = False 383 | for p in pt_pos: 384 | # Check if the torpedo has reached the point at which it dives towards the floor of the trench 385 | if p[ 2 ] - pt_launch_position >= PROTON_TORPEDO_RANGE_M: 386 | p[ 1 ] += PROTON_TORPEDO_VELOCITY_MS * 0.5 / fps 387 | else: 388 | p[ 2 ] += PROTON_TORPEDO_VELOCITY_MS / fps 389 | 390 | # Check if the torpedo has hit the floor of the trench 391 | if p[ 1 ] > TRENCH_HEIGHT_M / 2: 392 | hw = EXHAUST_PORT_WIDTH_M / 2 393 | z = EXHAUST_PORT_POSITION_M 394 | ex1 = -hw 395 | ex2 = hw 396 | ez1 = z - hw 397 | ez2 = z + hw 398 | # Check if torpedo entirely fit within the exhaust port 399 | if p[ 0 ] - PROTON_TORPEDO_RADIUS_M >= ex1 and \ 400 | p[ 0 ] + PROTON_TORPEDO_RADIUS_M <= ex2 and \ 401 | p[ 2 ] - PROTON_TORPEDO_RADIUS_M >= ez1 and \ 402 | p[ 2 ] + PROTON_TORPEDO_RADIUS_M <= ez2: 403 | bullseye = True 404 | hit = True 405 | if hit: 406 | pt_pos = [] # Delete the torpedos 407 | if bullseye: 408 | set_message( "Great shot kid - That was one in a million" ) 409 | explosion_countdown = 180 410 | else: 411 | set_message( "Negative - It just impacted off the surface" ) 412 | 413 | # Keep the ship within the bounds of the trench. 414 | def constrain_ship(): 415 | tw = TRENCH_WIDTH_M // 2 416 | th = TRENCH_HEIGHT_M // 2 417 | 418 | # Keep the ship within the horizontal span of the trench 419 | m = SHIP_WIDTH_M / 2 420 | if pos[ 0 ] < ( -tw + m ): 421 | pos[ 0 ] = -tw + m 422 | elif pos[ 0 ] > ( tw - m ): 423 | pos[ 0 ] = tw - m 424 | 425 | # Keep the ship within the vertical span of the trench 426 | m = SHIP_HEIGHT_M / 2 427 | if pos[ 1 ] < ( -th + m ) and pt_launch_position < 0: # Allow the ship to leave the trench after it has launched the torpedoes 428 | pos[ 1 ] = -th + m 429 | elif pos[ 1 ] > ( th - m ): 430 | pos[ 1 ] = th - m 431 | 432 | # Determine whether the ship has collided with any blocks 433 | def check_for_collisions(): 434 | global dead 435 | 436 | if current_barrier_index < len( barriers ): 437 | barrier = barriers[ current_barrier_index ] 438 | 439 | # Check if we are in the same Z position as the barrier 440 | if pos[ 2 ] > barrier[ 0 ] and pos[ 2 ] < barrier[ 0 ] + barrier[ 1 ]: 441 | # Calculate the area that our ship occupies 442 | x1 = pos[ 0 ] - SHIP_WIDTH_M / 2.0 443 | x2 = x1 + SHIP_WIDTH_M 444 | y1 = pos[ 1 ] - SHIP_HEIGHT_M / 2.0 445 | y2 = y1 + SHIP_HEIGHT_M 446 | 447 | # Calculate block size 448 | bw = TRENCH_WIDTH_M / 3.0 449 | bh = TRENCH_HEIGHT_M / 3.0 450 | bhw = bw / 2.0 451 | bhh = bh / 2.0 452 | for by in range( -1, 2 ): 453 | by1 = by * bh - bhh 454 | by2 = by1 + bh 455 | 456 | # Check to see whether we intersect vertically 457 | if y1 < by2 and y2 > by1: 458 | for bx in range( -1, 2 ): 459 | block_index = ( by + 1 ) * 3 + bx + 1 460 | if barrier[ 2 ][ block_index ] == 1: 461 | bx1 = bx * bw - bhw 462 | bx2 = bx1 + bw 463 | 464 | # Check to see whether we intersect horizontally 465 | if x1 < bx2 and x2 > bx1: 466 | set_message( "Game Over" ) 467 | dead = True 468 | 469 | def generate_messages(): 470 | global reached_launch_position 471 | 472 | if not reached_launch_position and is_close_to_launch_position(): 473 | reached_launch_position = True 474 | set_message( "You're all clear kid, now let's\nblow this thing and go home" ) 475 | 476 | # This is the main game processing function. 477 | def render_game( canvas ): 478 | global game_mode 479 | 480 | if not dead: 481 | move_ship() 482 | move_torpedoes() 483 | constrain_ship() 484 | check_for_collisions() 485 | generate_messages() 486 | elif message_delay <= 0: 487 | game_mode = MODE_INTRO 488 | render_death( canvas ) 489 | render_trench( canvas ) 490 | render_barriers( canvas ) 491 | render_exhaust_port( canvas ) 492 | render_torpedoes( canvas ) 493 | render_distance( canvas ) 494 | render_message( canvas ) 495 | 496 | if pos[ 2 ] > TRENCH_LENGTH_M + 60: 497 | game_mode = MODE_VICTORY if explosion_countdown > 0 else MODE_INTRO 498 | 499 | def render_deathstar( canvas, fill_colour = None ): 500 | centre = get_canvas_centre() 501 | radius = DEATH_STAR_RADIUS 502 | if fill_colour == None: 503 | canvas.draw_circle( centre, radius, LINE_WIDTH, DEATH_STAR_COLOUR, "Black" ) 504 | canvas.draw_circle( ( centre[ 0 ] - radius * 0.35, centre[ 1 ] - radius * 0.5 ), radius * 0.2, LINE_WIDTH, DEATH_STAR_COLOUR ) 505 | canvas.draw_line( ( centre[ 0 ] - radius, centre[ 1 ] - 3 ), ( centre[ 0 ] + radius, centre[ 1 ] - 3 ), LINE_WIDTH, DEATH_STAR_COLOUR ) 506 | canvas.draw_line( ( centre[ 0 ] - radius, centre[ 1 ] + 3 ), ( centre[ 0 ] + radius, centre[ 1 ] + 3 ), LINE_WIDTH, DEATH_STAR_COLOUR ) 507 | else: 508 | canvas.draw_circle( centre, radius, 1, fill_colour, fill_colour ) 509 | 510 | def render_stars( canvas ): 511 | star_colours = [] 512 | for shade in range( 8, 16 ): 513 | component = hex( 16 * shade ) 514 | colour = "#" + component + component + component 515 | star_colours.append( colour ) 516 | 517 | i = 0 518 | l = len( star_colours ) 519 | for star in stars: 520 | canvas.draw_circle( star, 1, 1, star_colours[ i % l ] ) 521 | i += 1 522 | 523 | def draw_text_centre( canvas, text, y, size, colour ): 524 | centre = get_canvas_centre() 525 | pos = ( centre[ 0 ] - frame.get_canvas_textwidth( text, size, FONT_STYLE ) // 2, y ) 526 | canvas.draw_text( text, pos, size, colour, FONT_STYLE ) 527 | 528 | def draw_text_right( canvas, text, x, y, size, colour ): 529 | pos = ( x - frame.get_canvas_textwidth( text, size, FONT_STYLE ), y ) 530 | canvas.draw_text( text, pos, size, colour, FONT_STYLE ) 531 | 532 | def render_intro_text( canvas ): 533 | centre = get_canvas_centre() 534 | draw_text_centre( canvas, "Star Wars", 190, 58, INTRO_TEXT_COLOUR ) 535 | draw_text_centre( canvas, "Press Space to begin your attack run", 340, 24, INTRO_TEXT_COLOUR ) 536 | draw_text_centre( canvas, "Use Cursor Keys to move", 420, 19, INTRO_TEXT_COLOUR ) 537 | draw_text_centre( canvas, "Use Space to launch Proton Torpedo", 440, 19, INTRO_TEXT_COLOUR ) 538 | draw_text_centre( canvas, "Thanks to Joe, Scott, John, Stephen & Rice University for providing a fantastic 'Introduction to Python' Course", 580, 16, INTRO_TEXT_COLOUR ) 539 | draw_text_right( canvas, VERSION, CANVAS_WIDTH - 16, 14, 14, INTRO_TEXT_COLOUR ) 540 | 541 | x1 = centre[ 0 ] - 160 542 | y1 = centre[ 1 ] + ( 185 if violent_death else 205 ) 543 | x2 = centre[ 0 ] + 160 544 | y2 = centre[ 1 ] + 225 545 | canvas.draw_polygon( ( ( x1, y1 ), ( x2, y1 ), ( x2, y2 ), ( x1, y2 ) ), 1, "Black", "Black" ) 546 | draw_text_centre( canvas, "Press 'Q' to turn " + ( "OFF" if violent_death else "ON" ) + " flashing colours", 520, 18, WARNING_TEXT_COLOUR ) 547 | if violent_death: 548 | draw_text_centre( canvas, "Note: this game contains flashing colours which are not suitable for sufferers of epilepsy", 500, 18, WARNING_TEXT_COLOUR ) 549 | 550 | def create_particles(): 551 | global particles 552 | 553 | radius = DEATH_STAR_RADIUS 554 | particles = [] 555 | for i in range( 0, 500 ): 556 | a = random.random() * 2 * math.pi 557 | m = random.random() 558 | x = math.sin( a ) * m * radius 559 | y = math.cos( a ) * m * radius 560 | particles.append( [ x, y ] ) 561 | 562 | def render_particles( canvas ): 563 | c = get_canvas_centre() 564 | for p in particles: 565 | x = p[ 0 ] + c[ 0 ] 566 | y = p[ 1 ] + c[ 1 ] 567 | canvas.draw_circle( ( x, y ), 1, 1, PARTICLE_COLOUR ) 568 | 569 | def move_particles(): 570 | c = get_canvas_centre() 571 | for p in particles: 572 | x = p[ 0 ] + c[ 0 ] 573 | y = p[ 1 ] + c[ 1 ] 574 | if x >= 0 and x < CANVAS_WIDTH and y >= 0 and y < CANVAS_HEIGHT: 575 | v = 1.1 576 | p[ 0 ] *= v 577 | p[ 1 ] *= v 578 | 579 | def render_victory( canvas ): 580 | global game_mode, explosion_countdown 581 | 582 | render_stars( canvas ) 583 | if explosion_countdown <= 0: 584 | if explosion_countdown > -160: 585 | base_colour = ( 64, 32, 16 ) 586 | factor = -explosion_countdown / 10.0 587 | colour = "#" 588 | for c in range( 0, 3 ): 589 | colour += hex( base_colour[ c ] * factor ) 590 | render_deathstar( canvas, colour ) 591 | elif explosion_countdown == -160: 592 | create_particles() 593 | elif explosion_countdown > -400: 594 | render_particles( canvas ) 595 | move_particles() 596 | else: 597 | game_mode = MODE_INTRO 598 | else: 599 | render_deathstar( canvas ) 600 | explosion_countdown -= 1 601 | 602 | def render_intro( canvas ): 603 | render_stars( canvas ) 604 | render_deathstar( canvas ) 605 | render_intro_text( canvas ) 606 | 607 | def update_time(): 608 | global last_time, message_delay, fps 609 | t = time.time() 610 | if last_time > 0: 611 | delta = ( t - last_time ) 612 | fps = 1.0 / delta 613 | if message_delay > 0: 614 | message_delay -= delta 615 | last_time = t 616 | 617 | def render( canvas ): 618 | update_time() 619 | if game_mode == MODE_GAME: 620 | render_game( canvas ) 621 | elif game_mode == MODE_VICTORY: 622 | render_victory( canvas ) 623 | elif game_mode == MODE_INTRO: 624 | render_intro( canvas ) 625 | 626 | def key_event( key, down ): 627 | global game_mode, violent_death 628 | 629 | if game_mode == MODE_GAME: 630 | factor = 1 if down else 0 631 | if key == simplegui.KEY_MAP[ "left" ]: 632 | acc[ 0 ] = -ACCELERATION_MSS * factor 633 | if key == simplegui.KEY_MAP[ "right" ]: 634 | acc[ 0 ] = ACCELERATION_MSS * factor 635 | if key == simplegui.KEY_MAP[ "up" ]: 636 | acc[ 1 ] = -ACCELERATION_MSS * factor 637 | if key == simplegui.KEY_MAP[ "down" ]: 638 | acc[ 1 ] = ACCELERATION_MSS * factor 639 | if key == simplegui.KEY_MAP[ "space" ]: 640 | launch_proton_torpedoes() 641 | elif down and game_mode == MODE_INTRO: 642 | if key == simplegui.KEY_MAP[ "space" ]: 643 | init_game() 644 | elif down and game_mode == MODE_VICTORY and explosion_countdown <= 0: 645 | game_mode = MODE_INTRO 646 | if down and key == simplegui.KEY_MAP[ "Q" ]: 647 | violent_death = not violent_death 648 | 649 | def key_down( key ): 650 | key_event( key, True ) 651 | 652 | def key_up( key ): 653 | key_event( key, False ) 654 | 655 | create_stars() 656 | 657 | # Create a frame and assign callbacks to event handlers 658 | frame = simplegui.create_frame( "Star Wars", CANVAS_WIDTH, CANVAS_HEIGHT ) 659 | frame.set_draw_handler( render ) 660 | frame.set_keydown_handler( key_down ) 661 | frame.set_keyup_handler( key_up ) 662 | 663 | # Start the frame animation 664 | frame.start() 665 | --------------------------------------------------------------------------------