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)
Related
I want to add the tree sprite to the sprite group named tree_group
I expect the distance of the trees spawning is calculated like this: if 800 - (tree.x + TREE_HEIGHT) > Tree.get_distance(score): tree_group.draw(tree)
For some reason, the trees are not appearing and I believe that this is because the tree sprite is not in the group yet, that is why I want to use the add() function.
I want the draw_display function to iterate over all the trees currently on the screen and move them using the get_speed equation.
My code is this:
import pygame
import sys
import random
import os
import time
from pygame.event import post
# initializes pygame libraries
pygame.init()
pygame.font.init()
pygame.mixer.init()
score = 0
FPS = 60
VEL = 5
# region | main window attributes and background
WIDTH, HEIGHT = 800, 800
display = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ski Game")
BACKGROUND = pygame.transform.scale(pygame.image.load(os.path.join("background.jpg")), (WIDTH, HEIGHT))
# endregion
# region | fonts and colors
SCORE_FONT = pygame.font.SysFont('comicsans', 40)
GAME_OVER_FONT = pygame.font.SysFont('comicsans', 100)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# endregion
# region | linking sprites and resizing then
SKIER_WIDTH = 65
SKIER_HEIGHT = 105
SKIER = pygame.transform.scale(pygame.image.load(
os.path.join("skier.png")), (SKIER_WIDTH, SKIER_HEIGHT))
# endregion
clock = pygame.time.Clock()
done = False
# create a custom event
CRASH_TREE = pygame.USEREVENT + 1
def draw_display(score, skier):
# blits the background
display.blit(BACKGROUND, (0, 0))
score_text = SCORE_FONT.render("Score: " + str(score), 1, BLACK)
display.blit(score_text, (WIDTH / 2 - score_text.get_width()/2, 10))
# blit skier
display.blit(SKIER, (skier.x, skier.y))
# blit trees
tree = Tree(score)
tree_group = pygame.sprite.Group()
tree_group.draw(display)
if score == 0:
tree_group.add(tree)
score += 1
elif 800 - (tree.rect.x + 150) > tree.get_distance(score):
tree_group.add(tree)
score += 1
pygame.display.update()
class Tree(pygame.sprite.Sprite):
def __init__(self, score):
super().__init__()
self.TREE_WIDTH = 80
self.TREE_HEIGHT = 150
self.image = pygame.transform.scale(pygame.image.load(os.path.join("tree.png")), (self.TREE_WIDTH, self.TREE_HEIGHT))
self.rect = self.image.get_rect()
self.rect.x = random.randrange(0, WIDTH)
self.rect.y = 700
print("init")
def get_speed(self, score, base=2, interval=10, multiplier=0.05):
return base + ((score//interval) * multiplier)
def get_distance(self, score, base=100, interval=10, multiplier=5):
return base + ((score//interval) * multiplier)
def update(self):
self.rect.y -= self.get_speed(score)
print("update")
def handle_skier_movement(keys_pressed, skier):
if keys_pressed[pygame.K_LEFT] and skier.x - VEL > 0: # LEFT
skier.x -= VEL
if keys_pressed[pygame.K_RIGHT] and skier.x + VEL + skier.width < WIDTH: # RIGHT
skier.x += VEL
if keys_pressed[pygame.K_UP] and skier.y - VEL > 0: # UP
skier.y -= VEL
if keys_pressed[pygame.K_DOWN] and skier.y + VEL + skier.width < WIDTH: # DOWN
skier.y += VEL
def game_over():
game_over_text = GAME_OVER_FONT.render("GAME OVER", 1, BLACK)
display.blit(game_over_text, (WIDTH/2 - game_over_text.get_width() /
2, HEIGHT/2 - game_over_text.get_height()/2))
pygame.display.update()
pygame.time.delay(5000)
def main():
skier = pygame.Rect(700, 300, SKIER_WIDTH, SKIER_HEIGHT)
score = 0
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
keys_pressed = pygame.key.get_pressed()
handle_skier_movement(keys_pressed, skier)
draw_display(score, skier)
tree = Tree(score)
tree.update()
if event.type == CRASH_TREE:
game_over()
score = 0
break
if __name__ == "__main__":
main()
In your draw_display function, you are first drawing the group and then adding the elements. That way, you are only drawing an empty group, and thus nothing happens. You should therefore place the tree_group.draw(display) line after the elif statement, right before pygame.display.update() line.
I am a noob in pygame and i have a problem. Pygame logo changes after a while. I have two images. Pls help! First image is how the window should look like and the second image is my window after 20 sec. What schould i do? I never had this problem and i tried so many things but i can't do it.
import pygame
import random
# initialize idk pygame.init()
# size Width = 800 Height = 600 white = (255, 255, 255) icon = pygame.image.load('sunflower.png') player_img =
pygame.image.load('cat.png') enemy1_img = pygame.image.load('dog.png')
FPS = 120 Vel = 5
# enemy random coordinates enemy1_X = random.randint(64, 736) enemy1_Y = random.randint(50, 150)
# screen def screen_f(p_rect, e_rect):
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('dog destroyer')
icon = pygame.image.load('sunflower.png')
pygame.display.set_icon(icon)
backgroud = pygame.image.load('backg.png')
screen.blit(backgroud, (0, 0))
screen.blit(player_img, (p_rect))
screen.blit(enemy1_img, (e_rect))
# player def player_movement(key_pressed, p_rect):
if key_pressed[pygame.K_RIGHT]:
p_rect.x += Vel
if key_pressed[pygame.K_LEFT]:
p_rect.x -= Vel
if key_pressed[pygame.K_UP]:
p_rect.y -= Vel
if key_pressed[pygame.K_DOWN]:
p_rect.y += Vel
def borders(p_rect):
if p_rect.x < 0:
p_rect.x = 0
elif p_rect.x > 735:
p_rect.x = 735
elif p_rect.y < 0:
p_rect.y = 0
elif p_rect.y > 535:
p_rect.y = 535
# main def main():
Vel_e = 4 # enemy velocity
player_rect = pygame.Rect(368, 500, 64, 64)
enemy_rect = pygame.Rect(enemy1_X, enemy1_Y, 64, 64)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
key_pressed = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
enemy_rect.x += Vel_e
if enemy_rect.x >= 736:
Vel_e = -4
enemy_rect.y += 50
if enemy_rect.x < 0:
Vel_e = 4
enemy_rect.y += 50
borders(player_rect)
player_movement(key_pressed, player_rect)
screen_f(player_rect, enemy_rect)
pygame.display.update()
if __name__ == "__main__":
main()
Before
After 20 seconds
your code is not clearly visible but i think i know how to fix it.
you usually want to set your screen and other important stuf right at the beginning of your file, not in a def that has to be called.
try it like this:
import pygame
pygame.init()
width = ...
height = ...
fps = ...
#set any colors
#load all you pictures
screen = pygame.display.set_mode((width, height))
# you would also want to set your caption and icon here so:
pygame.display.set_caption('your caption')
pygame.display.set_icon(icon)
#all your defs
#and when its all set you go to a main loop.
#(at the bottom of your file)
main()
# and quit for if the user quits and run gets set to False
pygame.quit()
quit()
I tried to build a simple game in python using pygame. At first my problem was to make the movement more smooth, because about every second the movement of the rectangles stuck for a few milliseconds. Then I found an solution by adding "os.environ['SDL_VIDEODRIVER'] = 'directx'" in to my code and changing the display mode to "FULLSCREEN" and "DOUBLEBUFF". The movement is more fluid now, but whenever I Alt + Tab out of the fullscreen game, i get this error:
Traceback (most recent call last):
File "C:\Users\L-Tramp-GAMING\Documents\Python\Game\Main_Game.py", line 64, in <module>
screen.fill(BG_COLOR)
pygame.error: IDirectDrawSurface3::Blt: Surface was lost
I don't know how to bypass this problem. I am also wondering if i can somehow run the game in windowed mode with the directx line added in normal speed. At the moment the game runs in much higher speed when it is in windowed mode. I hope some of you guys can help me. Thank you, Paul
import pygame
import random
import os
#Variables
WIDTH = 1280
HEIGHT = 720
GAME_OVER = False
BG_COLOR = (0, 0, 20)
playerWidth = 50
playerHeight = 50
playerPosX = WIDTH / 2 - playerWidth / 2
playerPosY = HEIGHT - (playerHeight + 75)
playerSpeed = 10
enemieWidth = 75
enemieHeight = 75
enemiePosX = random.randint(0, WIDTH - enemieWidth)
enemiePosY = 0
enemieSpeed = 5
enemieCounter = 1
####################################################################################################
os.environ['SDL_VIDEODRIVER'] = 'directx'
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN | pygame.DOUBLEBUF)
pygame.display.set_caption("Game")
pygame.key.set_repeat(1, 10)
clock = pygame.time.Clock()
#GameLoop
while not GAME_OVER:
for e in pygame.event.get():
if e.type == pygame.QUIT:
GAME_OVER = True
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_a:
playerPosX -= playerSpeed
print(hex(screen.get_flags() & 0xFFFFFFFF))
if e.key == pygame.K_d:
playerPosX += playerSpeed
#Graphics
screen.fill(BG_COLOR)
player = pygame.draw.rect(screen, (0, 255, 0), (playerPosX, playerPosY, playerWidth, playerHeight))
if enemiePosY < HEIGHT:
enemie = pygame.draw.rect(screen, (255, 0, 0), (enemiePosX, enemiePosY, enemieWidth, enemieHeight))
enemiePosY += enemieSpeed
else:
enemieCounter += 1
enemiePosY = 0
enemiePosX = random.randint(0, WIDTH - enemieWidth)
if (enemieCounter + 1) % 2 == 0:
pass
#End Graphics
pygame.display.flip()
Your movement lag was caused by pygame.key.set_repeat. To allow the player to hold down a and d to move you can update the players position in your game loop instead of using set_repeat by keeping track of a speed variable. If you wanted to use os.environ for another reason besides fixing the lag then this won't work but otherwise this should be fine.
import pygame
import random
import os
#Variables
WIDTH = 1280
HEIGHT = 720
GAME_OVER = False
BG_COLOR = (0, 0, 20)
playerWidth = 50
playerHeight = 50
playerPosX = WIDTH / 2 - playerWidth / 2
playerPosY = HEIGHT - (playerHeight + 75)
playerSpeed = 10
enemieWidth = 75
enemieHeight = 75
enemiePosX = random.randint(0, WIDTH - enemieWidth)
enemiePosY = 0
enemieSpeed = 5
enemieCounter = 1
####################################################################################################
#os.environ['SDL_VIDEODRIVER'] = 'directx'
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Game")
#pygame.key.set_repeat(1, 10) <----- This line is the problem
clock = pygame.time.Clock()
#GameLoop
speed = 0
while not GAME_OVER:
for e in pygame.event.get():
if e.type == pygame.QUIT:
GAME_OVER = True
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_a:
speed = -playerSpeed
if e.key == pygame.K_d:
speed = +playerSpeed
playerPosX += speed
#Graphics
screen.fill(BG_COLOR)
player = pygame.draw.rect(screen, (0, 255, 0), (playerPosX, playerPosY, playerWidth, playerHeight))
if enemiePosY < HEIGHT:
enemie = pygame.draw.rect(screen, (255, 0, 0), (enemiePosX, enemiePosY, enemieWidth, enemieHeight))
enemiePosY += enemieSpeed
else:
enemieCounter += 1
enemiePosY = 0
enemiePosX = random.randint(0, WIDTH - enemieWidth)
if (enemieCounter + 1) % 2 == 0:
pass
#End Graphics
pygame.display.flip()
Can the code handle the error, and then try re-creating the screen object ?
This is the same sort of process as when switching from full-screen to windowed.
EDIT: Added some code from the PyGame Wiki: https://www.pygame.org/wiki/toggle_fullscreen to hopefully work around further issues from OP's comment.
try:
screen.fill(BG_COLOR)
except pygame.error as e:
# Get the size of the screen
screen_info= pygame.display.Info()
cursor = pygame.mouse.get_cursor() # Duoas 16-04-2007
new_width = screen_info.current_w
new_height = screen_info.current_h
# re-initialise the display, creating a re-sizable window
pygame.display.quit()
pygame.display.init()
screen = pygame.display.set_mode( ( new_width, new_height ), pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE )
pygame.key.set_mods( 0 ) # HACK: work-a-round for a SDL bug??
pygame.mouse.set_cursor( *cursor ) # Duoas 16-04-2007
# did it work?
screen.fill(BG_COLOR)
I want to know if my enemy is within 200 pixels of a defense tower so that I can start taking lives of the enemy. The enemy is moving and the defense is still FYI. if anyone can give me advice on how to do this that would be amazing. If I put my code up it will just confuse everyone because my code is very messy so just give me advice on how to do it thanks. Nick. I have added my code because I know I have done something wrong if anyone has the time to read through it and tell me what I am doing wrong which is probably everything that would be much appreciated.
import pygame
import math
from pygame.locals import *
def text():
font = pygame.font.SysFont("monospace", 14)
text = font.render("Start Round", True, black)
textpos = text.get_rect()
textpos.center = (790,675)
Background.blit(text, textpos)
def newRound():
pos = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if 730 < pos[0] < 850 and 650 < pos[1] < 800:
pygame.draw.rect(Background, (150,150,150), (730,650,120,50))
if click[0] == 1:
startGame()
else:
pygame.draw.rect(Background, (100,100,100), (730,650,120,50))
def startGame():
global startRound, endRound, intro
intro = 0
createRound()
intro = 1
startRound = True
endRound = False
def lifeText(lifes):
font = pygame.font.SysFont("monospace", 20)
text = font.render("Lives %s" % (lifes) , True, black)
textpos = text.get_rect()
textpos.center = (60,30)
Background.blit(text, textpos)
def life(self):
global hit, endRound, startRound, noEnemies, lifes
if noEnemies == 0 and lifes > 0:
startRound = False
endRound = True
if self.rect.x == 960:
hit = hit + 1
lifes = lifes - 1
if lifes == 0:
print("You have 0 lives Game Over")
pygame.quit()
if hit == 4:
startRound = False
endRound = True
hit = 0
noEnemies = noEnemies + 1
def createRound():
global enemies, noEnemies
enemies = []
x = -40
y = 210
for e in range(noEnemies):
x = x - 80
enemies.append(yellowEnemy(x, y, Background))
noEnemies = len(enemies)
def displayTower():
for tower in towers:
Background.blit(redtower, (tower))
class yellowEnemy(object):
image1 = pygame.image.load("enemySpriteFullHealth.jpg")
image2 = pygame.image.load("enemySpriteHalfHealth.jpg")
image3 = pygame.image.load("enemySpriteDead.jpg")
def __init__(self, x, y, Background):
self.Background = Background
self.Background_rect = Background.get_rect()
self.rect = self.image1.get_rect()
self.rect = self.image2.get_rect()
self.rect = self.image3.get_rect()
self.rect.x = x
self.rect.y = y
self.health = 20
self.dist_x = 2
self.dist_y = 0
def update(self):
self.rect.x += self.dist_x
self.rect.y += self.dist_y
def draw(self, Background):
timeDead = 0
if self.health > 9 and self.health < 21:
Background.blit(self.image1, self.rect)
elif self.health < 10 and self.health > 1:
Background.blit(self.image2, self.rect)
elif self.health < 1:
Background.blit(self.image3, self.rect)
self.dist_x = 0
life(self)
pygame.init()
width = 960
height = 720
black = (0,0,0)
lifes = 10
hit = 0
intro = 1
FPS = 200
noEnemies = 4
bx = 1000
by = 1000
towers = []
endRound = True
startRound = False
clicked = False
mx, my = pygame.mouse.get_pos()
clock = pygame.time.Clock()
test= False
mapImg = pygame.image.load("mapimage.jpg")
redtower = pygame.image.load("redTower.jpg")
Background = pygame.display.set_mode((width, height))
Background_rect = Background.get_rect()
while intro == 1:
mousePos = pygame.mouse.get_pos()
mousePressed = pygame.mouse.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if 530 < mousePos[0] < 590 and 650 < mousePos[1] < 710:
if mousePressed[0] == 1:
clicked = True
if clicked == True:
mx, my = pygame.mouse.get_pos()
pygame.display.update()
bx = 30
by = 30
if mousePressed[0] == 0:
clicked = False
tx = mx - bx
ty = my - by
towerCords = tx, ty
towers.append(towerCords)
if endRound == True:
Background.blit(mapImg, (0,0))
newRound()
text()
if startRound == True:
for enemy in enemies:
enemy.update()
Background.blit(mapImg, (0,0))
for enemy in enemies:
enemy.draw(Background)
Background.blit(redtower, (mx-bx, my-by))
if clicked == True:
pygame.draw.circle(Background, (220, 0, 0), (mx, my), 200, 4)
displayTower()
lifeText(lifes)
Background.blit(redtower, (530,650))
pygame.display.update()
clock.tick(FPS)
To find the distance between 2 points, you can use this code:
def get_dist(pos1, pos2):
return math.hypot(pos1[0] - pos2[0], pos1[1] - pos2[1])
This also requires you to import math at the beginning of your program.
If they are sprites, you can simply do:
import math
defense_rect = defense.get_rect()
if math.abs(enemy.rect.center - defense_rect.rect.center) <= 200:
# *do something*
The logic is to see if the enemy's center is 200 pixels from the defense's center from any position (hence the usage of math.abs() which is absolute value). When it is, you replace the comment with your code. Why does this work?
Check here.
Pygame has pygame.Rect() to keep object position and size.
Tower 200x200 with top left corner in point (0,0)
tower_rect = pygame.Rect(0,0, 300, 300)
or you can move it to have (0,0) in center
tower_rect = pygame.Rect(0,0, 300, 300)
tower_rect.center = (0, 0)
To check if other Rect() is fully inside tower
enemy_rect = pygame.Rect(10, 10, 50, 50)
if tower_rect.contains(enemy_rect):
or if it fully or only partially in tower (it coollides with tower)
if tower_rect.colliderect(enemy_rect):
You can event test with list of enemies
if tower_rect.collidelistall(list_of_enemies_rect):
or check one enemy with all towers
if enemy_rect.collidelistall(list_of_towers_rect):
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()