Pygame drawing doesn't work correctly - python

I have a problem with drawing a simple rectangle on the screen. I've no clue why it fails to draw, I've tried several things: drawing it on the background surface, changing the order of the function calls etc. but it just doesn't seem to draw anything. As you can see, the enemy() method is supposed to draw a red rectangle, instead it draws nothing. The game runs fine otherwise. I'm sure its something simple I've overlooked.. frustrating!
import pygame
from pygame.locals import *
from pygame.time import *
from pygame.font import *
from pygame.draw import *
import sys
pygame.font.init()
pygame.init()
screen = pygame.display.set_mode((700,300))
pygame.display.set_caption('something')
#--------------------------------------------------------------------
velX = 0
velY = 0
playerx = 20
player_filename = 'player.png'
player = pygame.image.load(player_filename)
playery = 150
clock = pygame.time.Clock()
#--------------------------------------------------------------------
def draw():
global velX
global velY
global playerx
global playery
red = pygame.Color(255,0,0)
black = pygame.Color(0,0,0)
level = "1"
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255,255,255))
screen.blit(background, (0,0))
playerx = playerx + velX
playery = playery + velY
screen.blit(player, (playerx,playery))
font = pygame.font.Font(None, 36)
text = font.render(level, 1, black)
screen.blit(text, (670,10))
pygame.display.flip()
#--------------------------------------------------------------------
def enemySquares():
enemySurf = pygame.Surface(screen.get_size())
red = pygame.Color(255,0,0)
enemy = pygame.Rect(200,50,20,20)
pygame.draw.rect(enemySurf, red, enemy, 0)
#--------------------------------------------------------------------
def collisionWithBorder():
if playerx > 680 or playerx < 0:
pygame.quit()
sys.exit()
if playery > 280 or playery < 0:
pygame.quit()
sys.exit()
#--------------------------------------------------------------------
def playerFunc():
keys_down = pygame.key.get_pressed()
pygame.key.set_repeat(1,50)
time = 50/1000
global velX
global velY
direction = -1
if keys_down[K_d]:
direction = 0
if keys_down[K_a]:
direction = 3
if keys_down[K_w]:
direction = 1
if keys_down[K_s]:
direction = 2
if direction == 0:
velX = 50*time
velY = 0
if direction == 1:
velY = -50*time
velX = 0
if direction == 2:
velY = 50*time
velX = 0
if direction == 3:
velX = -50*time
velY = 0
#--------------------------------------------------------------------
def main():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
clock.tick(50)
collisionWithBorder()
draw()
playerFunc()
enemySquares()
#--------------------------------------------------------------------
if __name__ == '__main__':
main()

def enemySquares():
enemySurf = pygame.Surface(screen.get_size())
red = pygame.Color(255,0,0)
enemy = pygame.Rect(200,50,20,20)
pygame.draw.rect(enemySurf, red, enemy, 0)
The function above does draw a red rectangle - on a new surace it creates, not on
the "screen" surface.
Just drop your enemySurf = ... line there and change pygame.draw.rect(enemySurf, red, enemy, 0)
to
pygame.draw.rect(screen, red, enemy, 0) to have the rectangle apear on the next call to pygame.display.flip()

Related

How do I make sprites in pygame not move through eachother?

I'm making a game in pygame and I'm having some trouble with object collisions.
import pygame, sys
from pygame.math import Vector2
pygame.init()
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()
#Environment Variables
gravity = -1
jumpForce = 20
moveSpeed = 10
#Game Objects
playerPos = Vector2(230,230)
playerVelo = Vector2(0,0)
player = pygame.Rect(playerPos.x,playerPos.y, 20, 20)
boxPos = Vector2(350,480)
box = pygame.Rect(boxPos.x, boxPos.y, 20,20)
def Clamp(var, minClamp, maxClamp):
if minClamp > maxClamp:
raise Exception("minClamp must be less than maxClamp")
if var < minClamp:
var = minClamp
if var > maxClamp:
var = maxClamp
return var
def Draw():
global player,box
screen.fill((255,255,25))
player = pygame.Rect(playerPos.x,playerPos.y, 20, 20)
pygame.draw.rect(screen,(0,100,255),player)
box = pygame.Rect(boxPos.x, boxPos.y, 20,20)
pygame.draw.rect(screen,(10,200,20),box)
def PlayerVelocity():
global playerPos,playerVelo,player,box,boxPos
if player.colliderect(box):
playerPos = Vector2(boxPos.x,boxPos.y-20)
print("balls")
if playerPos.y < 499:
playerVelo.y += gravity
#if not pygame.Rect(playerPos.x+playerVelo.x,playerPos.y+playerVelo.y,20,20).colliderect(box):
playerPos -= playerVelo
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
playerVelo.y = jumpForce
print(playerVelo)
keys = pygame.key.get_pressed()
if keys[pygame.K_a] or keys[pygame.K_LEFT]:
playerVelo.x = 1*moveSpeed
elif keys[pygame.K_d] or keys[pygame.K_RIGHT]:
playerVelo.x = -1*moveSpeed
else:
playerVelo.x = 0
#Draw things to the screen
Draw()
PlayerVelocity()
playerPos.x = Clamp(playerPos.x, 0, 480)
playerPos.y = Clamp(playerPos.y,0,480)
pygame.display.update()
clock.tick(30)
I've tried looking this up and the other solutions either don't work with the movement system I've implemented or I just plain don't understand them.
It is not enough to change the position of the player when the player hits the obstacle. You need to constrain the player's box (pygame.Rect object) with the obstacle rectangle and update the player's position. Clamp and calculate the position of the player before checking for collision:
def PlayerVelocity():
global playerPos,playerVelo,player,box,boxPos
prev_y = playerPos.y
if playerPos.y < 499:
playerVelo.y += gravity
playerPos -= playerVelo
playerPos.x = Clamp(playerPos.x, 0, 480)
playerPos.y = Clamp(playerPos.y, 0, 480)
player = pygame.Rect(playerPos.x, playerPos.y, 20, 20)
box = pygame.Rect(boxPos.x, boxPos.y, 20,20)
if player.colliderect(box):
if prev_y+20 <= box.top:
player.bottom = box.top
elif player.left < box.left:
player.right = box.left
else:
player.left = box.right
playerPos = Vector2(player.topleft)
print("balls")

Not able to shoot bullet in pygame

So recently I have been trying to make my first big game but I'm stuck on the shooting phase. Basically, my problem is I want to make it so that I can shoot multiple bullets and move around while doing so, but I can't seem to figure it out.
Code:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
pygame.display.set_caption("Shooter Game!")
#Variables
playerX = 5
playerY = 5
black = (0,0,0)
blue = (0,0,255)
red = (255,0,0)
clicking = False
bulletX = playerX
bulletY = playerY
#End Of Variables#
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
screen.fill(blue)
player = pygame.image.load("Young_Link_2D.png").convert_alpha()
screen.fill(blue)
player1 = pygame.transform.scale(player, (100,100))
screen.blit(player1,(playerX,playerY))
keyPressed = pygame.key.get_pressed()
#Controls
if keyPressed[pygame.K_a]:
playerX -= 1
bulletX = playerX
if keyPressed[pygame.K_d]:
playerX += 1
bulletX = playerX
if keyPressed[pygame.K_w]:
playerY -= 1
bulletY = playerY
if keyPressed[pygame.K_s]:
playerY += 1
bulletY = playerY
#End of Controls
#Shooting
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
Bullet = pygame.draw.rect(screen, red, (bulletX+35,bulletY + 60,10,25))
bulletY = bulletY + 1
pygame.display.update()
Here is what i meant by classes:
import pygame
import Bullet
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Shooter Game!")
# Variables
playerX = 5
playerY = 5
black = (0, 0, 0)
blue = (0, 0, 255)
red = (255, 0, 0)
clicking = False
bulletX = playerX
bulletY = playerY
bullets = []
newBullet = False
# End Of Variables#
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
screen.fill(blue)
player = pygame.image.load("100x100_logo.png").convert_alpha()
screen.fill(blue)
player1 = pygame.transform.scale(player, (100, 100))
screen.blit(player1, (playerX, playerY))
keyPressed = pygame.key.get_pressed()
# Controls
if keyPressed[pygame.K_a]:
playerX -= 1
bulletX = playerX
if keyPressed[pygame.K_d]:
playerX += 1
bulletX = playerX
if keyPressed[pygame.K_w]:
playerY -= 1
bulletY = playerY
if keyPressed[pygame.K_s]:
playerY += 1
bulletY = playerY
# End of Controls
# Shooting
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
bullets.append(Bullet.Bullet(bulletX + 35, bulletY + 60))
for i in range(len(bullets)):
bullets[i].draw(screen, (255, 0, 0))
bullets[i].move(1)
print(len(bullets))
pygame.display.update()
Thats your main code. There is still a bug where there is no cooldown so multiple bullets are created consecutively when holding the mouse button.
import pygame
class Bullet:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self, win, colour):
pygame.draw.rect(win, colour, (self.x, self.y, 10, 25))
def move(self, speed):
self.y += speed
and thats the bullet class to create multiple instances
See How do I stop more than 1 bullet firing at once? and How can i shoot a bullet with space bar?.
You need to manage the bullets in a list:
bullets = []
Add a new bullet to the list when the mouse click is detected. Use pygame.Rect objects to represent the bullets. The events must be handled in the event loop:
for event in pygame.event.get():
# [...]
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
bullets.append(pygame.Rect(playerX, playerY, 35, 60))
Move the bullets in a loop. Remove the bullets from the list, when they when they move off the screen. See How to remove items from a list while iterating?:
for bullet in bullets[:]:
bullet.y += 5
if bullet.top > 600:
bullets.remove(bullet)
Draw all the bullets in the list in another loop:
for bullet in bullets:
pygame.draw.rect(screen, red, bullet)
Complete example:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
pygame.display.set_caption("Shooter Game!")
#Variables
player = pygame.image.load("Young_Link_2D.png").convert_alpha()
playerX, playerY = 5, 5
black = (0,0,0)
blue = (0,0,255)
red = (255,0,0)
clicking = False
bullets = []
#End Of Variables#
clock = pygame.time.Clock()
running = True
while running:
clock.tick(100)
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
bullets.append(pygame.Rect(playerX, playerY, 35, 60))
keyPressed = pygame.key.get_pressed()
playerX += keyPressed[pygame.K_d] - keyPressed[pygame.K_a]
playerY += keyPressed[pygame.K_s] - keyPressed[pygame.K_w]
for bullet in bullets[:]:
bullet.y += 5
if bullet.top > 600:
bullets.remove(bullet)
screen.fill(blue)
player1 = pygame.transform.scale(player, (100,100))
screen.blit(player1,(playerX,playerY))
for bullet in bullets:
pygame.draw.rect(screen, red, bullet)
pygame.display.update()
pygame.quit()
exit()

Flickering Sprite in Pygame

I know lots of people have had issues with flickering images in pygame on here, but none of the responses have helped me. I am trying to make Space Invaders, however, the bullet flickers as it moves up the screen. Please try to help me, and thank you! I do not currently care about the size, position, or scale of the bullet, I know it does not look great, but I just want it to display properly! Below is the code:
import pygame
#import sys- might use later
import random
#Sets the starting values for screen, etc. of the playing space
pygame.init()
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Space Invaders")
play = True
clock = pygame.time.Clock()
blkColor = (0, 0, 0)
#Loads and sizes the alien and player ship(s)
playerShip = pygame.image.load('ship.png')
playerShip = pygame.transform.scale(playerShip, (50, 50))
playerX = 370
playerY = 520
alien = pygame.image.load('alien.png')
alien = pygame.transform.scale(alien, (35, 35))
alienX = random.randint(0, 750)
alienY = 0
move = 5
alienMove = 5
bullet = pygame.image.load('bullet.png')
bullet = pygame.transform.scale(bullet, (5, 100))
bulletX = 0
bulletY = 600
hit = False
fire = False
hitRangeMin = -35
hitRangeMax = 35
score = 0
def player():
screen.blit(playerShip, (playerX, playerY))
def enemy():
screen.blit(alien, (alienX, alienY))
def alienMovement():
global alienX
global alienY
global alienMove
#Moves the alien across the screen; when it hits the edge, it shifts down one spot and goes the other direction
alienX += alienMove
if alienX > 750:
alienMove = -5
alienY += 35
if alienX < 0:
alienMove = 5
alienY += 35
def shoot(x, y):
global fire
global bulletY
fire = True
screen.blit(bullet, (x, y))
pygame.display.flip()
if bulletY < 0:
fire = False
bulletY = 550
elif bulletY >= 0:
fire = True
def gameOver(score):
print('Will add score and display and stuff- does noo matter.')
# Keeps the game window open until exited
while not hit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
player()
enemy()
key_input = pygame.key.get_pressed()
if key_input[pygame.K_LEFT]:
playerX -= move
elif key_input[pygame.K_RIGHT]:
playerX += move
if playerX > 800:
playerX = 0
if playerX < 0:
playerX = 800
#For shooting the bullet
if key_input[pygame.K_SPACE]:
bulletX = playerX + 23
shoot(bulletX, bulletY)
##Loops with function "shoot" to move bullet up the screen
if fire:
shoot(bulletX, bulletY)
bulletY -= 5
screen.fill(blkColor)
alienMovement()
player()
enemy()
pygame.display.flip()
clock.tick(60)
The problem is caused by multiple calls to pygame.display.update(). An update of the display at the end of the application loop is sufficient. Multiple calls to pygame.display.update() or pygame.display.flip() cause flickering.
Remove pygame.display.flip() from shoot:
def shoot(x, y):
global fire
global bulletY
fire = True
screen.blit(bullet, (x, y))
# pygame.display.flip() <--- DELETE
if bulletY < 0:
fire = False
bulletY = 550
elif bulletY >= 0:
fire = True
And you have to clear the screen before drawing the bullet:
while not hit:
# [...]
screen.fill(blkColor) # <--- INSERT
if key_input[pygame.K_SPACE]:
bulletX = playerX + 23
shoot(bulletX, bulletY)
##Loops with function "shoot" to move bullet up the screen
if fire:
shoot(bulletX, bulletY)
bulletY -= 5
# screen.fill(blkColor) <--- DELETE
alienMovement()
player()
enemy()
pygame.display.flip()
clock.tick(60)

Pygame Multiple bullets not spawning

So im new at pygame and coding my first project- a side scrolling shooter. The issue im having is with my bullets: when i press the space key, some of the bullets will show up but there are times when nothing happens, and no bullets spawn when i jump. Not quite sure how to go about fixing this issue- any ideas would be greatly appreciated.
Code is as follows:
import pygame
import math, random, sys, pygame.mixer
from pygame.locals import *
pygame.init()
pygame.mixer.pre_init(44100, -16, 2, 8192)
pygame.mixer.init()
jump = False
jump_offset = 0
jump_height = 250
k = pygame.key.get_pressed()
def events():
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
def do_jumping():
global jump_height
global jump
global jump_offset
if jump:
jump_offset += 3
if jump_offset >= jump_height:
jump = False
elif jump_offset > 0 and jump == False:
jump_offset -= 3
#Defining colours
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
#Window Settings
w = 1280
h = 720
half_w = w /2
half_h = h /2
AREA = w*h
#Initialising the window
pygame.init()
display = pygame.display.set_mode((w,h)) #Sets the size of the window
pygame.display.set_caption("Cattleman") #Sets the title of the window
Clock = pygame.time.Clock() #clockspeed for the game ie. 60fps
FPS = 600
#pygame.mouse.set_visible(True) #Allows the mouse to be shown in the game window.
background = pygame.image.load("background.png").convert()
backgroundWidth, backgroundHeight = background.get_rect().size
stageWidth = backgroundWidth*2 #sets the area which the player can move in
stagePosX = 0 #Records position of stage as the player moves
startScrollPosX = half_w
circleRadius = 25
circlePosX = circleRadius
playerPosX = circleRadius
playerPosY = 602
playerVelocityX = 0
playersprite = pygame.image.load("player_spriteR2.png").convert_alpha()
playersprite = pygame.transform.scale(playersprite, (130,130))
bullets = []
bulletSprite = pygame.image.load("Bullet1.png").convert_alpha()
bulletSprite = pygame.transform.scale(bulletSprite, (20,10))
#Sounds
#gunSounds = ["pew1.wav", "pew2.wav", "pew3.wav", "pew4.wav"]
#SOUNDS
shot = pygame.mixer.Sound("pew1.wav")
#------------------------MAIN PROGRAM LOOP------------------------#
while True:
events()
do_jumping()
k = pygame.key.get_pressed()
if k[K_RIGHT]:
playerVelocityX = 2 #Moves the player right
playersprite = pygame.image.load("player_spriteR2.png").convert_alpha()
playersprite = pygame.transform.scale(playersprite, (130,130))
if k[K_LEFT]:
playerVelocityX = -2 #Moves the player left
playersprite = pygame.image.load("player_spriteL2.png").convert_alpha()
playersprite = pygame.transform.scale(playersprite, (130,130))
if k[K_UP] and jump == False and jump_offset == 0:
jump = True
if not k[K_RIGHT] and not k[K_LEFT]:
playerVelocityX = 0 #If no input detected, the player does not move
if k[K_SPACE]:
for event in pygame.event.get():
bullets.append([circlePosX-100, playerPosY-20])
shot.play()
playerPosX += playerVelocityX
if playerPosX > stageWidth - circleRadius-25: playerPosX = stageWidth - circleRadius-25 #Checks if the player trie to go past the right boundary
if playerPosX < circleRadius+55:playerPosX = circleRadius+55 #Checks if the player tries to go past the left boundary
if playerPosX < startScrollPosX: circlePosX = playerPosX
elif playerPosX > stageWidth - startScrollPosX: circlePosX = playerPosX - stageWidth + w
else:
circlePosX = startScrollPosX
stagePosX += -playerVelocityX
for b in range(len(bullets)):
bullets[b][0] -= 3
for bullet in bullets[:]:
if bullet[0] < 0:
bullets.remove(bullet)
rel_x = stagePosX % backgroundWidth
display.blit(background,(rel_x - backgroundWidth, 0))
if rel_x < w:
display.blit(background, (rel_x, 0))
for bullet in bullets:
display.blit(bulletSprite, pygame.Rect(bullet[0], bullet[1], 0, 0,))
#pygame.draw.circle(display,WHITE, (int(circlePosX),playerPosY - jump_offset), circleRadius, 0)
display.blit(playersprite, (int(circlePosX-80),playerPosY-100 - jump_offset))
pygame.display.update()
Clock.tick(FPS)
display.fill(BLACK)
I have done this in my code that leaves multiple balls similar like bullets :
class Bullet():
def __init__(self, x, y):
# self.image = pygame.image.load("SingleBullet.png")
self.image = pygame.image.load("ball.png")
self.image = pygame.transform.scale(self.image, (25, 25))
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
self.is_alive = True
# --------------------
def update(self):
self.rect.y -= 15
if self.rect.y < 0:
self.is_alive = False
# --------------------
def draw(self, screen):
screen.blit(self.image, self.rect.topleft)
for getting keyboard :
def event_handler(self, event):
if event.type == KEYDOWN:
if event.key == K_LEFT:
self.move_x = -5
elif event.key == K_RIGHT:
self.move_x = 5
elif event.key == K_SPACE:
if len(self.shots) < self.max_shots:
self.shots.append(Bullet(self.rect.centerx, self.rect.top))
if event.type == KEYUP:
if event.key in (K_LEFT, K_RIGHT):
self.move_x = 0

pygame window collison bug

I made a moveable white tank using the arrow keys. I made some collision detection so that the 'tank' wouldn't go out the screen. The only places where the collision doesn't work is when the 'tank' is positioned near the corners and when pressed up or down respective to top and bottom, it falls out of the window. Any ideas how to fix this? Collision code is in def drawtank().
import pygame, sys
from pygame.locals import *
FPS = 30
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
TANK_SIZE = 20
BLACK = (0 ,0 ,0 )
WHITE = (255,255,255)
def drawArena():
DISPLAYSURF.fill(BLACK)
def drawTank(tank):
if tank.bottom > WINDOW_HEIGHT:
tank.bottom = WINDOW_HEIGHT
elif tank.top < 0:
tank.top = 0
elif tank.right > WINDOW_WIDTH:
tank.right = WINDOW_WIDTH
elif tank.left < 0:
tank.left = 0
pygame.draw.rect(DISPLAYSURF, WHITE, tank)
def main():
pygame.init()
global DISPLAYSURF
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Tanks')
tankX = 200
tankY = 200
tankX_change = 0
tank = pygame.Rect(tankX, tankY, TANK_SIZE, TANK_SIZE)
drawArena()
drawTank(tank)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
keys_pressed = pygame.key.get_pressed()
if keys_pressed[K_LEFT]:
tankX -= 20
if keys_pressed[K_RIGHT]:
tankX += 20
if keys_pressed[K_UP]:
tankY -=20
if keys_pressed[K_DOWN]:
tankY += 20
tank = pygame.Rect(tankX, tankY, TANK_SIZE, TANK_SIZE)
drawArena()
drawTank(tank)
pygame.display.update()
FPSCLOCK.tick(FPS)
if __name__ == '__main__':
main()
You need if/elif's for each possibility, elif tank.right > WINDOW_WIDTH is only evaluated of the previous if and elif is False so you miss when the tank in in the corner:
def drawTank(tank):
if tank.bottom > WINDOW_HEIGHT:
tank.bottom = WINDOW_HEIGHT
elif tank.top < 0:
tank.top = 0
if tank.right > WINDOW_WIDTH: # need an if here
tank.right = WINDOW_WIDTH
elif tank.left < 0:
tank.left = 0
pygame.draw.rect(DISPLAYSURF, WHITE, tank)
You don't need the one extra if as the tank cannot be at the top and bottom of the screen simultaneously.
There is an easier way though:
screen = pygame.display.set_mode((800, 600)) # add this
screen_rect = screen.get_rect() # this
Now your code is:
import pygame, sys
from pygame.locals import *
FPS = 30
TANK_SIZE = 20
BLACK = (0 ,0 ,0 )
WHITE = (255,255,255)
screen=pygame.display.set_mode((800, 600))
screen_rect=screen.get_rect()
def drawArena():
screen.fill(BLACK)
def drawTank(tank):
tank.clamp_ip(screen_rect)
pygame.draw.rect(screen, WHITE, tank)
def main():
pygame.init()
FPSCLOCK = pygame.time.Clock()
pygame.display.set_caption('Tanks')
tankX = 200
tankY = 200
tankX_change = 0
tank = pygame.Rect(tankX, tankY, TANK_SIZE, TANK_SIZE)
drawArena()
drawTank(tank)
......
I'm not familiar with pygame. But, could there be more than one arrow key pressed prior to a call to drawTank? If so, the fact that things are happening close to the corners suggests to me that perhaps the tank is moved to a position to the left of the box and below the box (for example). Then the if ... elif that you call will only correct one of those errors.
If that's it, just turn every elif in drawtank to if:
def drawTank(tank):
if tank.bottom > WINDOW_HEIGHT:
tank.bottom = WINDOW_HEIGHT
if tank.top < 0:
tank.top = 0
if tank.right > WINDOW_WIDTH:
tank.right = WINDOW_WIDTH
if tank.left < 0:
tank.left = 0
pygame.draw.rect(DISPLAYSURF, WHITE, tank)

Categories