

{"id":108572,"date":"2022-06-22T08:00:19","date_gmt":"2022-06-22T02:30:19","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=108572"},"modified":"2026-06-01T14:05:11","modified_gmt":"2026-06-01T08:35:11","slug":"python-tank-game-project","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/","title":{"rendered":"Tank Game in Python with Source Code"},"content":{"rendered":"<div class='__iawmlf-post-loop-links' style='display:none;' data-iawmlf-post-links='[{&quot;id&quot;:2586,&quot;href&quot;:&quot;https:\\\/\\\/drive.google.com\\\/file\\\/d\\\/1HETIZFqkaSfSINbjZHAYFzpCLqQ-p4Ia\\\/view?usp=drive_link&quot;,&quot;archived_href&quot;:&quot;http:\\\/\\\/web-wp.archive.org\\\/web\\\/20260601083457\\\/https:\\\/\\\/drive.google.com\\\/file\\\/d\\\/1HETIZFqkaSfSINbjZHAYFzpCLqQ-p4Ia\\\/view?usp=drive_link&quot;,&quot;redirect_href&quot;:&quot;&quot;,&quot;checks&quot;:[{&quot;date&quot;:&quot;2026-06-01 23:07:34&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-05 15:42:57&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-09 01:48:05&quot;,&quot;http_code&quot;:200}],&quot;broken&quot;:false,&quot;last_checked&quot;:{&quot;date&quot;:&quot;2026-06-09 01:48:05&quot;,&quot;http_code&quot;:200},&quot;process&quot;:&quot;done&quot;}]'><\/div>\n<p>Have you ever played a tank game? If not, do play this interesting game with the computer by building it on your own. So, let\u2019s not wait and create Tank Game using Python.<\/p>\n<h3>What is a Tank Game?<\/h3>\n<p>A tank game is a video game where a player plays with the computer and tries to reduce the power by attacking the opponent\u2019s tank by firing. Similarly, the computer tries to reduce the player&#8217;s power.<\/p>\n<h3>Tank Game in Python<\/h3>\n<p>We build this game using the Pygame module. In this, the player uses the keyboard button to control the game as follows:<\/p>\n<ul>\n<li>Right and left arrows to move the tank<\/li>\n<li>Up and down arrows to move the turret<\/li>\n<li>a and d keys to reduce and increase the power respectively<\/li>\n<li>Space to fire<\/li>\n<\/ul>\n<h3>Download Tank Game Code<\/h3>\n<p>Please download the source code for the tank game using the link: <a href=\"https:\/\/drive.google.com\/file\/d\/1HETIZFqkaSfSINbjZHAYFzpCLqQ-p4Ia\/view?usp=drive_link\"><strong>Tank Game Project<\/strong><\/a><\/p>\n<h3>Project Prerequisites<\/h3>\n<p>The developers are expected to have prior knowledge of the Pygame module to build this project. You can also install this module using the below command.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">pip install pygame<\/pre>\n<h3>Steps to build Python Tank Game<\/h3>\n<p>We follow the below steps to build the tank game using Pygame:<\/p>\n<p>1. First, we download modules<\/p>\n<p>2. Then we write the code to initiate the pygame and create global variables<\/p>\n<p>3. After this, we write functions to add information to screen<\/p>\n<p>4. Next, we create the button class<\/p>\n<p>5. Now we create the function to create the main window<\/p>\n<p>6. And then the controls window<\/p>\n<p>7. Now we create a function to create tank<\/p>\n<p>8. Next, we create the function to create the explosion<\/p>\n<p>9. Then we create a function to fire for both the players<\/p>\n<p>10. We now create the functions for game over and pause conditions<\/p>\n<p>11. Finally, we create the main window<\/p>\n<h3>1. Importing Python modules for Tank Game Project<\/h3>\n<p>First, we import the required modules. The pygame module is the main one that we use to build the game.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import pygame\r\nimport time\r\nimport random\r\n<\/pre>\n<h3>2. Initiating pygame and global variables<\/h3>\n<p>Now, we initiate the pygame module, set dimensions, and add the caption. We also create some global variables to set other dimensions for tank, turret, and base ground.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">pygame.init()\r\n\r\nwidth = 800\r\nheight = 600\r\n\r\ngameWin = pygame.display.set_mode((width, height))\r\npygame.display.set_caption('DataFlair Tanks Game')\r\nclock = pygame.time.Clock()\r\n\r\ntankWidth = 40\r\ntankHeight = 20\r\nturretWidth = 5\r\nwheelWidth = 5\r\ngroundHeight = 35\r\n<\/pre>\n<h3>3. Function to show text on screen<\/h3>\n<p>This is a basic function we create to add any text on the screen of required properties at specified location. We create this to reduce the redundancy by using just a link to add text.<\/p>\n<p>The function textObjects() creates the font object of the specified attributes. And we use the show_message() function to add the text object to the window at specified location.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def textObjects(text, color, size=\"small\"):\r\n    if size == \"vsmall\":\r\n        font=pygame.font.SysFont(\"Calibre\", 15)\r\n        textSurf = font.render(text, True, color)\r\n    if size == \"small\":\r\n        font=pygame.font.SysFont(\"Calibre\", 25)\r\n        textSurf = font.render(text, True, color)\r\n    if size == \"medium\":\r\n        font=pygame.font.SysFont(\"Calibre\", 35)\r\n        textSurf = font.render(text, True, color)\r\n    if size == \"large\":\r\n        font=pygame.font.SysFont(\"Calibre\", 50)\r\n        textSurf = font.render(text, True, color)\r\n    return textSurf, textSurf.get_rect()\r\n\r\ndef show_message(msg, color, y_displace=0, size=\"small\"):\r\n    textSurf, textRect = textObjects(msg, color, size)\r\n    textRect.center = (int(width \/ 2), int(height \/ 2) + y_displace)\r\n    gameWin.blit(textSurf, textRect)\r\n<\/pre>\n<h3>4. Creating button class<\/h3>\n<p>We create a Button class to name the buttons, place them on screen based on the position given. And then run the click() function to execute the respective function based on the \u2018action\u2019 property of that button clicked by using the action property.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Button:\r\n    \"\"\"Create a button, then blit the surface in the while loop\"\"\"\r\n \r\n    def __init__(self, text,pos, font, bg=\"blue\"):\r\n        self.x, self.y = pos\r\n        self.font = pygame.font.SysFont(\"Arial\", font)\r\n        self.text=text\r\n        self.text = self.font.render(self.text, 1, pygame.Color(\"blue\"))\r\n        self.change_text(bg)\r\n \r\n    def change_text(self, bg=\"blue\"):\r\n        self.size = self.text.get_size()\r\n        self.surface = pygame.Surface(self.size)\r\n        self.surface.fill(bg)\r\n        self.surface.blit(self.text, (0, 0))\r\n        self.rect = pygame.Rect(self.x, self.y, self.size[0], self.size[1])\r\n       \r\n \r\n    def show(self):\r\n        gameWin.blit(self.text , (self.x, self.y))\r\n \r\n    def click(self, event,action):\r\n        x, y = pygame.mouse.get_pos()\r\n        if event.type == pygame.MOUSEBUTTONDOWN:\r\n            if pygame.mouse.get_pressed()[0]:\r\n                if self.rect.collidepoint(x, y):\r\n                    if action == \"quit\":\r\n                        pygame.quit()\r\n                        quit()\r\n\r\n                    if action == \"controls\":\r\n                        controlsWin()\r\n\r\n                    if action == \"play\":\r\n                        mainGame()\r\n\r\n                    if action == \"main\":\r\n                        mainWindow()\r\n<\/pre>\n<h3>5. Creating main window function<\/h3>\n<p>Here, we create the main window with welcoming text and three buttons:<\/p>\n<p>a. \u2018Play\u2019 to start the game<\/p>\n<p>b. \u2018Controls\u2019 to see the guidelines<\/p>\n<p>c. \u2018Quit\u2019 to exit the game<\/p>\n<p>We create three button objects for the above actions.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def mainWindow ():\r\n    button1 = Button(\"Play\", (350, 350),  font=30)\r\n\r\n    button2 = Button(\"Controls\", (350, 430), font=30)\r\n\r\n    button3 = Button(\"Quit\", (350, 510), font=30)\r\n   \r\n\r\n    while True:\r\n        gameWin.fill('#ffffff')\r\n        Green = (0, 255, 0)\r\n        show_message(\"DataFlair Tank Game\", '#000000', -200, size=\"large\")\r\n        show_message(\"Welcome to the game!\", 'red', -100, size=\"medium\")\r\n        show_message(\"Choose any of the following to move forward\", 'red', -50, size=\"medium\")\r\n        for event in pygame.event.get():\r\n            if event.type == pygame.QUIT:\r\n                pygame.quit()\r\n            button1.click(event,'play')\r\n            button2.click(event,'controls')\r\n            button3.click(event,'quit')\r\n        button1.show()\r\n        button2.show()\r\n        button3.show()\r\n   \r\n        clock.tick(30)\r\n        pygame.display.update()\r\n<\/pre>\n<h3>6. Creating controls window function<\/h3>\n<p>Using controlsWin() function, we create the controls window with welcoming text and three buttons:<\/p>\n<p>d. \u2018Play\u2019 to start the game<\/p>\n<p>e. \u2018Main\u2019 to go to to main window<\/p>\n<p>f. \u2018Quit\u2019 to exit the game<\/p>\n<p>We create three button objects for the above actions<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def controlsWin():\r\n   \r\n    button1 = Button(\"Play\", (150, 500),  font=30)\r\n\r\n    button2 = Button(\"Main\", (350, 500), font=30)\r\n\r\n    button3 = Button(\"Quit\", (550, 500), font=30)\r\n   \r\n\r\n    while True:\r\n        gameWin.fill('#ffffff')\r\n        Green = (0, 255, 0)\r\n        show_message(\"DataFlair Tank Game\", '#000000', -200, size=\"large\")\r\n        show_message(\"Here are the instructions to play:\", 'red', -100, size=\"medium\")\r\n        show_message(\"The objective is to shoot and destroy the enemy tank before they destroy you.\", Green, -30)\r\n        show_message(\"Fire using the Spacebar\", 'gray', 0)\r\n        show_message(\"Move Turret using the Up and Down arrows\", Green, 30)\r\n        show_message(\"Move Tank using the  Left and Right arrows\", 'gray', 60)\r\n        show_message(\"Press D to raise Power AND Press A to reduce Power \", Green, 90)\r\n        show_message(\"Finally press P to pause\", 'gray', 120)\r\n        for event in pygame.event.get():\r\n            if event.type == pygame.QUIT:\r\n                pygame.quit()\r\n            button1.click(event,'play')\r\n            button2.click(event,'main')\r\n            button3.click(event,'quit')\r\n        button1.show()\r\n        button2.show()\r\n        button3.show()\r\n   \r\n        clock.tick(30)\r\n        pygame.display.update()\r\n<\/pre>\n<h3>7. Creating function for tank<\/h3>\n<p>This function creates a tank at a specified location. We use the circle() of pygame to add shape to the tank.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def tank(x, y, turPos,tank):\r\n    #tank=1 if player's tank and -1 if computer's tank\r\n    x = int(x)\r\n    y = int(y)\r\n    locs=[[27,2],[26,5],[25,8],[23,12],[20,14],[18,15],[15,17],[13,19],[11,21]]\r\n    possibleTurrets=[]\r\n    for i in locs:\r\n        possibleTurrets.append((x-tank*i[0],y-i[1]))\r\n\r\n    pygame.draw.circle(gameWin, '#000000', (x, y), int(tankHeight \/ 2))\r\n   \r\n    for i in range(-15,16,5):\r\n        pygame.draw.circle(gameWin,'#000000', (x+i, y + 20), wheelWidth)\r\n\r\n    return possibleTurrets[turPos]\r\n<\/pre>\n<h3>8. Creating function for explosion<\/h3>\n<p>This function connects the firing tank to the probable target location by drawing a curve with circles. This gives a clear picture of the shot made.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def explosion(x, y, size=50):\r\n    explode = True\r\n\r\n    while explode:\r\n        for event in pygame.event.get():\r\n            if event.type == pygame.QUIT:\r\n                pygame.quit()\r\n                quit()\r\n\r\n        startPoint = x, y\r\n\r\n        colorChoices = ['red', 'brown2', 'yellow', 'gold1']\r\n\r\n        magnitude = 1\r\n\r\n        while magnitude &lt; size:\r\n            exploding_bit_x = x + random.randrange(-1 * magnitude, magnitude)\r\n            exploding_bit_y = y + random.randrange(-1 * magnitude, magnitude)\r\n\r\n            pygame.draw.circle(gameWin, colorChoices[random.randrange(0, 4)], (exploding_bit_x, exploding_bit_y),\r\n                               random.randrange(1, 5))\r\n            magnitude += 1\r\n\r\n            pygame.display.update()\r\n            clock.tick(100)\r\n\r\n        explode = False\r\n<\/pre>\n<h3>9. Function to create the bar<\/h3>\n<p>Now, we create the bars of the player and the computer of the length and color based on the power left.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def show_health_bars(player_health, enemy_health):\r\n    if player_health &gt; 75:\r\n        player_color = 'green'\r\n    elif player_health &gt; 50:\r\n        player_color = 'yellow'\r\n    else:\r\n        player_color = 'red'\r\n\r\n    if enemy_health &gt; 75:\r\n        enemy_color = 'green'\r\n    elif enemy_health &gt; 50:\r\n        enemy_color = 'yellow'\r\n    else:\r\n        enemy_color = 'red'\r\n\r\n    pygame.draw.rect(gameWin, player_color, (680, 25, player_health, 25))\r\n    pygame.draw.rect(gameWin, enemy_color, (20, 25, enemy_health, 25))\r\n<\/pre>\n<h3>10. Creating a function to fire by player<\/h3>\n<p>This function runs when the player presses the spacebar indicating the fire action. In this function, we start from the position of the player. And then, we draw the trajectory based on the power set by the player and the angle of the turret.<\/p>\n<p>Then we check the distance of the hit from the computer\u2019s tank and calculate the reduction in the computer&#8217;s score. Finally, run the explosion() function to show the trajectory.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def fireShell(xy, tankx, tanky, turPos, gun_power, xlocation, barrier_width, randomHeight, enemyTankX, enemyTankY):\r\n    #pygame.mixer.Sound.play(fire_sound)\r\n    fire = True\r\n    damage = 0\r\n\r\n    startingShell = list(xy)\r\n\r\n    print(\"FIRE!\", xy)\r\n\r\n    while fire:\r\n        for event in pygame.event.get():\r\n            if event.type == pygame.QUIT:\r\n                pygame.quit()\r\n                quit()\r\n\r\n        # print(startingShell[0],startingShell[1])\r\n        pygame.draw.circle(gameWin, 'red', (startingShell[0], startingShell[1]), 5)\r\n\r\n        startingShell[0] -= (12 - turPos) * 2\r\n\r\n        # y = x**2\r\n        startingShell[1] += int(\r\n            (((startingShell[0] - xy[0]) * 0.015 \/ (gun_power \/ 50)) ** 2) - (turPos + turPos \/ (12 - turPos)))\r\n\r\n        if startingShell[1] &gt; height - groundHeight:\r\n            print(\"Last shell:\", startingShell[0], startingShell[1])\r\n            hit_x = int((startingShell[0] * height - groundHeight) \/ startingShell[1])\r\n            hit_y = int(height - groundHeight)\r\n            print(\"Impact:\", hit_x, hit_y)\r\n\r\n            if enemyTankX + 10 &gt; hit_x &gt; enemyTankX - 10:\r\n                print(\"Critical Hit!\")\r\n                damage = 25\r\n            elif enemyTankX + 15 &gt; hit_x &gt; enemyTankX - 15:\r\n                print(\"Hard Hit!\")\r\n                damage = 18\r\n            elif enemyTankX + 25 &gt; hit_x &gt; enemyTankX - 25:\r\n                print(\"Medium Hit\")\r\n                damage = 10\r\n            elif enemyTankX + 35 &gt; hit_x &gt; enemyTankX - 35:\r\n                print(\"Light Hit\")\r\n                damage = 5\r\n\r\n            explosion(hit_x, hit_y)\r\n            fire = False\r\n\r\n        check_x_1 = startingShell[0] &lt;= xlocation + barrier_width\r\n        check_x_2 = startingShell[0] &gt;= xlocation\r\n\r\n        check_y_1 = startingShell[1] &lt;= height\r\n        check_y_2 = startingShell[1] &gt;= height - randomHeight\r\n\r\n        if check_x_1 and check_x_2 and check_y_1 and check_y_2:\r\n            hit_x = int((startingShell[0]))\r\n            hit_y = int(startingShell[1])\r\n            explosion(hit_x, hit_y)\r\n            fire = False\r\n\r\n        pygame.display.update()\r\n        clock.tick(60)\r\n    return damage\r\n<\/pre>\n<h3>11. Creating a function to fire by computer<\/h3>\n<p>This function runs when it&#8217;s the computer&#8217;s chance to fire. In this, we set the power of the computer and then calculate the probable player\u2019s tank location. And then repeat the same function as fireShell().<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def compfireShell(xy, tankx, tanky, turPos, gun_power, xlocation, barrier_width, randomHeight, ptankx, ptanky):\r\n    damage = 0\r\n    currentPower = 1\r\n    power_found = False\r\n\r\n    while not power_found:\r\n        currentPower += 1\r\n        if currentPower &gt; 100\r\n            power_found = True\r\n\r\n        fire = True\r\n        startingShell = list(xy)\r\n\r\n        while fire:\r\n            for event in pygame.event.get():\r\n                if event.type == pygame.QUIT:\r\n                    pygame.quit()\r\n                    quit()\r\n\r\n\r\n            startingShell[0] += (12 - turPos) * 2\r\n            startingShell[1] += int(\r\n                (((startingShell[0] - xy[0]) * 0.015 \/ (currentPower \/ 50)) ** 2) - (turPos + turPos \/ (12 - turPos)))\r\n\r\n            if startingShell[1] &gt; height - height:\r\n                hit_x = int((startingShell[0] * height - height) \/ startingShell[1])\r\n                hit_y = int(height - height)\r\n                if ptankx + 15 &gt; hit_x &gt; ptankx - 15:\r\n                    print(\"target acquired!\")\r\n                    power_found = True\r\n                fire = False\r\n\r\n            check_x_1 = startingShell[0] &lt;= xlocation + barrier_width\r\n            check_x_2 = startingShell[0] &gt;= xlocation\r\n\r\n            check_y_1 = startingShell[1] &lt;= height\r\n            check_y_2 = startingShell[1] &gt;= height - randomHeight\r\n\r\n            if check_x_1 and check_x_2 and check_y_1 and check_y_2:\r\n                hit_x = int((startingShell[0]))\r\n                hit_y = int(startingShell[1])\r\n                fire = False\r\n\r\n    fire = True\r\n    startingShell = list(xy)\r\n    print(\"FIRE!\", xy)\r\n\r\n    while fire:\r\n        for event in pygame.event.get():\r\n            if event.type == pygame.QUIT:\r\n                pygame.quit()\r\n                quit()\r\n        pygame.draw.circle(gameWin, 'red', (startingShell[0], startingShell[1]), 5)\r\n\r\n        startingShell[0] += (12 - turPos) * 2\r\n\r\n        gun_power = random.randrange(int(currentPower * 0.90), int(currentPower * 1.10))\r\n\r\n        startingShell[1] += int(\r\n            (((startingShell[0] - xy[0]) * 0.015 \/ (gun_power \/ 50)) ** 2) - (turPos + turPos \/ (12 - turPos)))\r\n\r\n        if startingShell[1] &gt; height - groundHeight:\r\n            print(\"last shell:\", startingShell[0], startingShell[1])\r\n            hit_x = int((startingShell[0] * height - groundHeight) \/ startingShell[1])\r\n            hit_y = int(height - groundHeight)\r\n            print(\"Impact:\", hit_x, hit_y)\r\n\r\n            if ptankx + 10 &gt; hit_x &gt; ptankx - 10:\r\n                print(\"Critical Hit!\")\r\n                damage = 25\r\n            elif ptankx + 15 &gt; hit_x &gt; ptankx - 15:\r\n                print(\"Hard Hit!\")\r\n                damage = 18\r\n            elif ptankx + 25 &gt; hit_x &gt; ptankx - 25:\r\n                print(\"Medium Hit\")\r\n                damage = 10\r\n            elif ptankx + 35 &gt; hit_x &gt; ptankx - 35:\r\n                print(\"Light Hit\")\r\n                damage = 5\r\n\r\n            explosion(hit_x, hit_y)\r\n            fire = False\r\n\r\n        check_x_1 = startingShell[0] &lt;= xlocation + barrier_width\r\n        check_x_2 = startingShell[0] &gt;= xlocation\r\n\r\n        check_y_1 = startingShell[1] &lt;=height\r\n        check_y_2 = startingShell[1] &gt;= height - randomHeight\r\n\r\n        if check_x_1 and check_x_2 and check_y_1 and check_y_2:\r\n            print(\"Last shell:\", startingShell[0], startingShell[1])\r\n            hit_x = int((startingShell[0]))\r\n            hit_y = int(startingShell[1])\r\n            print(\"Impact:\", hit_x, hit_y)\r\n            explosion(hit_x, hit_y)\r\n            fire = False\r\n\r\n        pygame.display.update()\r\n        clock.tick(60)\r\n    return damage\r\n<\/pre>\n<h3>12. Functions for game over and pause conditions<\/h3>\n<p>The game_over() function runs when one of the player\u2019s scores is less than 0. We quit the game and show who is the winner. It also has three buttons to play again, show controls and quit.<\/p>\n<p>And the pause() function pause the game and give a chance to either continue or quit the game. The keyboard button \u2018c\u2019 is used to continue and \u2018q\u2019 to quit.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def game_over(winner):\r\n    button1 = Button(\"Play Again\", (350, 350),  font=30)\r\n\r\n    button2 = Button(\"Controls\", (350, 430), font=30)\r\n\r\n    button3 = Button(\"Quit\", (350, 510), font=30)\r\n    while True:\r\n            gameWin.fill('#ffffff')\r\n            Green = (0, 255, 0)\r\n            Red=(255,0,0)\r\n            text=''\r\n            color=''\r\n            if(winner == 1):\r\n                text=\"Congratulations, You Won!\"\r\n                color=Green\r\n            else:\r\n                text=\"Sorry, game over. Better luck next time!\"\r\n                color=Red\r\n            show_message(\"DataFlair Tank Game\", '#000000', -200, size=\"large\")\r\n            show_message(text, color, -100, size=\"medium\")\r\n            for event in pygame.event.get():\r\n                if event.type == pygame.QUIT:\r\n                    pygame.quit()\r\n                button1.click(event,'play')\r\n                button2.click(event,'controls')\r\n                button3.click(event,'quit')\r\n            button1.show()\r\n            button2.show()\r\n            button3.show()\r\n       \r\n            clock.tick(30)\r\n            pygame.display.update()\r\n\r\ndef pause():\r\n    paused = True\r\n    show_message(\"Paused\", 'white', -100, size=\"large\")\r\n    show_message(\"Press C to continue playing or Q to quit\", 'wheat', 25)\r\n    pygame.display.update()\r\n    while paused:\r\n        #gameDisplay.fill(black)\r\n        for event in pygame.event.get():\r\n\r\n            if event.type == pygame.QUIT:\r\n                pygame.quit()\r\n                quit()\r\n            if event.type == pygame.KEYDOWN:\r\n                if event.key == pygame.K_c:\r\n                    paused = False\r\n                elif event.key == pygame.K_q:\r\n                    pygame.quit()\r\n                    quit()\r\n\r\n        clock.tick(5)\r\n<\/pre>\n<h3>13. Function to create the main window<\/h3>\n<p>This is the main game window. In this function, we mainly check the button activity of the player. And do the respective activity based on the controls mentioned initially.<\/p>\n<p>We continually update the window based on the changes made by continuous firing, reducing score, moving tanks, and checking conditions to end the game.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def mainGame():\r\n    gameExit = False\r\n    gameOver = False\r\n\r\n    player_health = 100\r\n    enemy_health = 100\r\n\r\n    barrier_width = 50\r\n\r\n    mainTankX = width * 0.9\r\n    mainTankY = height * 0.9\r\n    tankMove = 0\r\n    currentTurPos = 0\r\n    changeTur = 0\r\n\r\n    enemyTankX = width * 0.1\r\n    enemyTankY = height * 0.9\r\n\r\n    fire_power = 50\r\n    power_change = 0\r\n\r\n    xlocation = (width \/ 2) + random.randint(int(-0.1 * width),int( 0.1 * width))\r\n    randomHeight = random.randint(int(height * 0.1), int(height * 0.6))\r\n\r\n    while True:\r\n        gameWin.fill('#ffffff')\r\n        Green = (0, 255, 0)\r\n        Red=(255,0,0)\r\n        text=''\r\n        color=''\r\n        show_message(\"DataFlair Tank Game\", '#000000', -200, size=\"large\")\r\n        for event in pygame.event.get():\r\n            if event.type == pygame.QUIT:\r\n                gameExit = True\r\n            if event.type == pygame.KEYDOWN:\r\n                if event.key == pygame.K_LEFT:\r\n                    tankMove = -5\r\n\r\n                elif event.key == pygame.K_RIGHT:\r\n                    tankMove = 5\r\n\r\n                elif event.key == pygame.K_UP:\r\n                    changeTur = 1\r\n\r\n                elif event.key == pygame.K_DOWN:\r\n                    changeTur = -1\r\n\r\n                elif event.key == pygame.K_p:\r\n                    pause()\r\n                elif event.key == pygame.K_SPACE:\r\n                    gameWin.fill('white')\r\n                    show_message(\"DataFlair Tank Game\", '#000000', -200, size=\"large\")\r\n                    show_health_bars(player_health, enemy_health)\r\n                    gun = tank(mainTankX, mainTankY, currentTurPos,1)\r\n                    enemy_gun = tank(enemyTankX, enemyTankY, 8,-1)\r\n                    fire_power += power_change\r\n                    font=pygame.font.SysFont(\"Calibre\", 30)\r\n                    text = font.render(\"Power: \" + str(fire_power) + \"%\", True, 'black')\r\n                    gameWin.blit(text, [width \/ 2, 0])\r\n                    text = font.render(\"Height: \" + str(currentTurPos) + \"%\", True, 'black')\r\n                    gameWin.blit(text, [width \/ 2, 20])\r\n                    pygame.draw.rect(gameWin, 'green', [xlocation, height - randomHeight, barrier_width, randomHeight])\r\n                    gameWin.fill('green',\r\n                                        rect=[0,height - groundHeight, width, height])\r\n                    pygame.display.update()\r\n\r\n                    clock.tick(30)\r\n                   \r\n                    damage = fireShell(gun, mainTankX, mainTankY, currentTurPos, fire_power, xlocation, barrier_width,\r\n                                       randomHeight, enemyTankX, enemyTankY)\r\n                    enemy_health -= damage\r\n\r\n                    possibleMovement = ['f', 'r']\r\n                    moveIndex = random.randrange(0, 2)\r\n\r\n                    for x in range(random.randrange(0, 10)):\r\n\r\n                        if width * 0.3 &gt; enemyTankX &gt; width * 0.03:\r\n                            if possibleMovement[moveIndex] == \"f\":\r\n                                enemyTankX += 5\r\n                            elif possibleMovement[moveIndex] == \"r\":\r\n                                enemyTankX -= 5\r\n\r\n                            gameWin.fill('white')\r\n                            show_message(\"DataFlair Tank Game\", '#000000', -200, size=\"large\")\r\n                            show_health_bars(player_health, enemy_health)\r\n                            gun = tank(mainTankX, mainTankY, currentTurPos,1)\r\n                            enemy_gun = tank(enemyTankX, enemyTankY, 8,-1)\r\n                            fire_power += power_change\r\n                            font=pygame.font.SysFont(\"Calibre\", 30)\r\n                            text = font.render(\"Power: \" + str(fire_power) + \"%\", True, 'black')\r\n                            gameWin.blit(text, [width \/ 2, 0])\r\n                            text = font.render(\"Height: \" + str(currentTurPos) + \"%\", True, 'black')\r\n                            gameWin.blit(text, [width \/ 2, 20])\r\n                            pygame.draw.rect(gameWin, 'green', [xlocation, height - randomHeight, barrier_width, randomHeight])\r\n                            gameWin.fill('green',\r\n                                             rect=[0,height - groundHeight, width, height])\r\n                            pygame.display.update()\r\n\r\n                            clock.tick(30)\r\n\r\n                    damage = compfireShell(enemy_gun, enemyTankX, enemyTankY, 8, 50, xlocation, barrier_width,\r\n                                         randomHeight, mainTankX, mainTankY)\r\n                    player_health -= damage\r\n               \r\n                elif event.key == pygame.K_a:\r\n                    power_change = -1\r\n                elif event.key == pygame.K_d:\r\n                    power_change = 1\r\n               \r\n            elif event.type == pygame.KEYUP:\r\n                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n                    tankMove = 0\r\n\r\n                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:\r\n                    changeTur = 0\r\n\r\n                if event.key == pygame.K_a or event.key == pygame.K_d:\r\n                    power_change = 0\r\n           \r\n\r\n        mainTankX += tankMove\r\n\r\n        currentTurPos += changeTur\r\n\r\n        if currentTurPos &gt; 8:\r\n            currentTurPos = 8\r\n        elif currentTurPos &lt; 0:\r\n            currentTurPos = 0\r\n\r\n        if mainTankX - (tankWidth \/ 2) &lt; xlocation + barrier_width:\r\n            mainTankX += 5\r\n   \r\n        show_health_bars(player_health, enemy_health)\r\n        gun = tank(mainTankX, mainTankY, currentTurPos,1)\r\n        enemy_gun = tank(enemyTankX, enemyTankY, 8,-1)\r\n\r\n        fire_power += power_change\r\n\r\n        if fire_power &gt; 100:\r\n            fire_power = 100\r\n        elif fire_power &lt; 1:\r\n            fire_power = 1\r\n               \r\n        font=pygame.font.SysFont(\"Calibre\", 30)\r\n        text = font.render(\"Power: \" + str(fire_power) + \"%\", True, 'black')\r\n        gameWin.blit(text, [width \/ 2, 0])\r\n        text = font.render(\"Height: \" + str(currentTurPos) + \"%\", True, 'black')\r\n        gameWin.blit(text, [width \/ 2, 20])\r\n        pygame.draw.rect(gameWin, 'green', [xlocation, height - randomHeight, barrier_width, randomHeight])\r\n        gameWin.fill('green',rect=[0,height - groundHeight, width, height])\r\n        if player_health &lt; 1 :\r\n            game_over(0)\r\n        elif enemy_health &lt; 1:\r\n            game_over(1)\r\n\r\n        pygame.display.update()\r\n        clock.tick(30)\r\n   \r\n\r\nmainWindow()\r\n<\/pre>\n<h3>\u00a0Python Tank Game Output<\/h3>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/05\/python-tank-game-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-110369\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/05\/python-tank-game-output.webp\" alt=\"python tank game output\" width=\"1000\" height=\"787\" \/><\/a><\/p>\n<h3>Summary<\/h3>\n<p>Hurray, we have built the tank game using Python! Hope you enjoyed building the game with us and also enjoy playing it.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Have you ever played a tank game? If not, do play this interesting game with the computer by building it on your own. So, let\u2019s not wait and create Tank Game using Python. What&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":110370,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46],"tags":[26334,27051,25791,21082,22734,27050,26741,26743,26742],"class_list":["post-108572","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-basic-python-project","tag-play-tank-game-in-python","tag-python-game-project","tag-python-project","tag-python-project-for-beginners","tag-python-tank-fight","tag-python-tank-game","tag-python-tank-game-project","tag-python-tank-game-with-source-code"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Tank Game in Python with Source Code - DataFlair<\/title>\n<meta name=\"description\" content=\"Create Tank Game using various Python modules. It is a video game where player tries to reduce power by attacking opponent\u2019s tank by firing.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Tank Game in Python with Source Code - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Create Tank Game using various Python modules. It is a video game where player tries to reduce power by attacking opponent\u2019s tank by firing.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2022-06-22T02:30:19+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-06-01T08:35:11+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/05\/python-game-project-tank-game.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Tank Game in Python with Source Code - DataFlair","description":"Create Tank Game using various Python modules. It is a video game where player tries to reduce power by attacking opponent\u2019s tank by firing.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/","og_locale":"en_US","og_type":"article","og_title":"Tank Game in Python with Source Code - DataFlair","og_description":"Create Tank Game using various Python modules. It is a video game where player tries to reduce power by attacking opponent\u2019s tank by firing.","og_url":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2022-06-22T02:30:19+00:00","article_modified_time":"2026-06-01T08:35:11+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/05\/python-game-project-tank-game.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/b49855299264df5e27e3ec6c2cd9fde9"},"headline":"Tank Game in Python with Source Code","datePublished":"2022-06-22T02:30:19+00:00","dateModified":"2026-06-01T08:35:11+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/"},"wordCount":932,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/05\/python-game-project-tank-game.webp","keywords":["basic python project","play tank game in python","python game project","Python project","python project for beginners","python tank fight","Python tank game","Python tank game project","Python tank game with source code"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/python-tank-game-project\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/","url":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/","name":"Tank Game in Python with Source Code - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/05\/python-game-project-tank-game.webp","datePublished":"2022-06-22T02:30:19+00:00","dateModified":"2026-06-01T08:35:11+00:00","description":"Create Tank Game using various Python modules. It is a video game where player tries to reduce power by attacking opponent\u2019s tank by firing.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/python-tank-game-project\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/05\/python-game-project-tank-game.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/05\/python-game-project-tank-game.webp","width":1200,"height":628,"caption":"python game project tank game"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/python-tank-game-project\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Python Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/python\/"},{"@type":"ListItem","position":3,"name":"Tank Game in Python with Source Code"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/b49855299264df5e27e3ec6c2cd9fde9","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/ef46b745ddad2fad690af626c6ef29b91809ad0a9f5ef398d07817d8cad042f5?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/ef46b745ddad2fad690af626c6ef29b91809ad0a9f5ef398d07817d8cad042f5?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/ef46b745ddad2fad690af626c6ef29b91809ad0a9f5ef398d07817d8cad042f5?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team is a group of passionate educators and industry experts dedicated to providing high-quality online learning resources on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. With years of experience in the field, the team aims to simplify complex topics and help learners advance their careers. At DataFlair, we believe in empowering students and professionals with the knowledge and skills needed to thrive in today\u2019s fast-paced tech industry. Follow us for Free courses, expert insights, tutorials, and practical tips to boost your learning journey.","url":"https:\/\/data-flair.training\/blogs\/author\/datafbdad\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/108572","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=108572"}],"version-history":[{"count":5,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/108572\/revisions"}],"predecessor-version":[{"id":148670,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/108572\/revisions\/148670"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/110370"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=108572"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=108572"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=108572"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}