4.6 - Example

4.6 Example

Here is the shortened code for the full tank game. We removed the class content, but we left the class declarations. The content for each of the classes is the same as shown in the previous sections. We shortened it because it was very long. To actually run the code, you can copy the code from GitHub or just instantiate your Tank_Game class and use its main loop.
""" This is a tank game made with pygame and original images. Brief description of classes within this file: Game_obj - the abstract base class for all the objects that appear on-screen, including the Tank class, the Bullet class, and the Target class Bullet - inherits from Game_obj. Target - inherits from Game_obj. It is always stationary. Tank - inherits from Game_obj. Takes keyboard input (W, A, S, and D) to control the tank's movement. App - the abstract base class for the actual Tank_game class. It's purpose is to define a structure for the game. Tank_game - the functional class that inherits from App. It creates a bullet whenever the mouse is clicked. It handles the collisions (if a bullet hits a target, both are deleted. If the tank runs into the target, the target is deleted.) """ import pygame from pygame.locals import ( K_w, K_s, K_a, K_d, KEYDOWN, KEYUP, QUIT, RESIZABLE, MOUSEBUTTONDOWN, ) import time import math import random BULLET_IMG_PATH = "./bullet.png" TARGET_IMG_PATH = "./target.png" TANK_IMG_PATH = "./completetank.png" BLACK = (255, 255, 255) DIRTBROWN = (168, 95, 0) SANDBROWN = (237, 201, 175) TANKSPEED = [2, 2] # speed x and speed y BULLETSPEED = [8, 8] class Game_obj: # content is in 4.2 - Object Class class Bullet(Game_obj): # content is in 4.3 class Target(Game_obj): # content is in 4.3 class Tank(Game_obj): # content is in 4.3 class App: # content is in 4.4 class Tank_Game(App): # content is in 4.5 game = Tank_Game() game.mainloop()
View full code and icons on Github
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.