Dec-22-2019, 12:55 AM
I'm in the very early stages of developing a duel-player tank game where there are two tanks, a map, and the objective is to shoot the other tank before they can to you. Right now, I'm really far off that goal as I've only been able to make a single tank rotate and set boundaries for the screen. The tank is just a small 16 x 16 sprite. My code seems a bit messy and I'm just wondering if someone can help me format by arranging the variables with classes and init (self) functions so I can add the projectiles, etc, more easily later on. Here is my code:
import pygame
import time
import math
import random
pygame.init()
display_width = 800
display_height = 600
white = (255, 255, 255)
black = (0,0,0)
tank_width = 20
tank_height = 20
gameDisplay = pygame.display.set_mode((display_width, display_height), 0, 32)
pygame.display.set_caption("Tank Game")
keys = [False, False, False, False, False]
tankPos = [100, 100]
tankImg = pygame.image.load('tank1.png')
clock = pygame.time.Clock()
def textBox(text,font):
theText = font.render(text, True, black)
return theText, theText.get_rect()
def redraw():
angle = 0
position = pygame.mouse.get_pos()
angle = math.atan2(position[1] - (tankPos[1] + 32), position[0] - (tankPos[0] + 26))
playerrot = pygame.transform.rotate(tankImg, 360 - angle*57.29)
tankPos1 = (tankPos[0] - playerrot.get_rect().width/2, tankPos[1] - playerrot.get_rect().height / 2)
gameDisplay.blit(playerrot, tankPos1)
def gameLoop():
x = (display_width * 0.03)
y = (display_height * 0.01)
xVelocity = 0
yVelocity = 0
tankImg = pygame.image.load('tank1.png')
gameExit = False
while gameExit == False:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
keys[0] = True
elif event.key == pygame.K_LEFT:
keys[1] = True
elif event.key == pygame.K_DOWN:
keys[2] = True
elif event.key == pygame.K_RIGHT:
keys[3] = True
elif event.key == pygame.K_SEMICOLON:
keys[4] == True
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
keys[0] = False
elif event.key == pygame.K_LEFT:
keys[1] = False
elif event.key == pygame.K_DOWN:
keys[2] = False
elif event.key == pygame.K_RIGHT:
keys[3] = False
elif event.key == pygame.K_COMMA:
keys[4] = False
if keys[0]:
tankPos[1] -= 5
elif keys[2]:
tankPos[1] += 5
elif keys[1]:
tankPos[0] -= 5
elif keys[3]:
tankPos[0] += 5
elif keys[4]:
projectiles()
x += xVelocity
y += yVelocity
gameDisplay.fill(white)
#tank(x,y,angle)
if (tankPos[0] > display_width - tank_width):
tankPos[0] = 766
if tankPos[0] < 0:
tankPos[0] = 30
if tankPos[1] < 0:
tankPos[1] = 6
if tankPos[1] > 596:
tankPos[1] = 594
clock.tick(60)
redraw()
gameLoop()
