I am building a game in pygame where there is a red target that moves up and down on the right side of the screen and a ship on the left side of the screen the moves up and down that fires bullets (which is just a blue rectangle) at the target.
My ship, and my target start in the center of each side of the screen and are properly moving. The problem that I have is when I 'fire' a bullet the bullet is getting drawn at the ship's original position, not where the ship has moved to on the screen.
I have the bullet's rect set to the ship image's rect outside of my while loop, but I would think that it would get updated as my ship moves up and down on the screen.
import pygame
import pygame.sprite
import sys
screen_width = 1200
screen_height = 800
screen = pygame.display.set_mode((screen_width, screen_height))
screen_rect = screen.get_rect()
image = pygame.image.load('ship.bmp')
image_rect = image.get_rect()
image_rect.midleft = screen_rect.midleft
target_rect = pygame.Rect(400, 0, 100, 100)
target_color = (255, 0, 0)
target_rect.midright = screen_rect.midright
target_direction = 1
bullet_rect = pygame.Rect(0, 0, 15, 3)
bullet_rect.midright = image_rect.midright
bullet_color = (0, 0, 255)
fire_bullet = False
while True:
screen.fill((0, 255, 0))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
sys.exit()
# Move the ship up and down
elif event.key == pygame.K_UP:
image_rect.y -= 45
elif event.key == pygame.K_DOWN:
image_rect.y += 45
# Active bullet fired
elif event.key == pygame.K_SPACE:
fire_bullet = True
elif event.type == pygame.QUIT:
sys.exit()
# Move the bullet across the screen if fired
if fire_bullet:
screen.fill(bullet_color, bullet_rect)
bullet_rect.x += 1
# Move the Target up and down
target_rect.y += target_direction
if target_rect.bottom >= screen_height:
target_direction *= -1
elif target_rect.top <= 0:
target_direction *= -1
screen.fill(target_color, target_rect)
screen.blit(image, image_rect)
pygame.display.flip()
I have the bullet's rect set to the ship image's rect outside of my while loop, but I would think that it would get updated as my ship moves up and down on the screen.
That's not it. You just set the position of the rect, there is not automatic update. You have to write the code to keep them in sync.
But even simpler, in your case you could create the bullet rect when you shot. Move the bullet creation in the loop like this:
elif event.key == pygame.K_SPACE:
bullet_rect = pygame.Rect(0, 0, 15, 3)
bullet_rect.midright = image_rect.midright
bullet_color = (0, 0, 255)
fire_bullet = True
Related
I am trying to move a sprite (called Player) to the left or right by pressing the arrow keys. The movement to the right or left would be made by changing the center of the rectangle of the sprite. As you might be able to see, I am trying to add/subtract 8 from the sprite's x coordinates in order to move it right or left. However, the sprite doesn't move when I hit an arrow key. How can I fix this?
import pygame
import random
import time
import pygame as pg
# set the width and height of the window
width = 800
height = 370
groundThickness = 30
pheight = 50
pwidth = 50
playerx = 0+pwidth
playery = height-groundThickness-pheight/2
fps = 30
# define colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (5, 35, 231)
# initialize pygame
pygame.init()
# initialize pygame sounds
pygame.mixer.init()
# create window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("my game")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((pwidth, pheight))
self.image.fill(red)
self.rect = self.image.get_rect()
self.rect.center = (playerx, playery)
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
# Game loop
running = True
x_change = 0
while running:
# keep loop running at the right speed
clock.tick(fps)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print("left")
x_change = -8
elif event.key == pygame.K_RIGHT:
print("right")
x_change = 8
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
print(x_change)
playerx += x_change
all_sprites.update()
#ground
pygame.draw.rect(screen, (0,255,0), ((0, height-groundThickness), (width, groundThickness)))
# Update
all_sprites.update()
# Draw / render
all_sprites.draw(screen)
pygame.display.update()
# AFTER drawing everything, flip the display
pygame.display.flip()
pygame.quit()
You've never altered the position of the sprite player.
How do you expect it to move?
All you've done is to change the value of your local variable playerx, but you've never pushed that change back into the sprite object.
Start by adding the middle line below:
playerx += x_change
player.rect.center = (playerx, playery)
all_sprites.update()
See how that alters things? Can you take it from there?
Filling the screen with your background color or image will also be needed to keep your screen updated with the current position of the moving sprite. The following command will be added at the top of your draw/render section of the game loop:
screen.fill(black)
I am trying to detect when two of my sprites collide. The first thing I did was create a rectangle around my player (called player.img) then another around the trees that I want to detect (called background.treesrect). I set the coordinates of the players rectangle equal to the coordinates that update when the player moves by the user pressing keys but the players rectangle doesnt move. Then I used the sprite.colliderect(sprite) function to detect if they collide and it doesnt detect. Can someone show my why my player rectangle isnt updating and anything else that may be wrong?
EDIT I just figured out the collision by putting the function that draws the rectangle into the game loop instead of the player class but I ran into another weird problem. The rectangle moves faster than the player sprite for some reason and I cant figure out how to make the player sprite on top of the background and not show the player rectangle.
import pygame
import sys
from pygame.locals import *
#starts the program
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
yellow = (255, 255, 153)
#creates a window of 800x600
setDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Menu')
img = pygame.image.load('C:\\Users\\Ben\\Documents\\sprite.png')
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.img = pygame.image.load('C:\\Users\\Ben\\Documents\\sprite.png').convert()
self.imgx = 10
self.imgy = 10
self.setDisplay = pygame.display.get_surface()
self.x = self.imgx
self.y = self.imgy
self.rect = pygame.draw.rect(setDisplay, pygame.Color(0, 0, 255), pygame.Rect(self.x, self.y, 32, 32))
def draw(self):
self.setDisplay.blit(self.img)
def load(self, filename):
self.img = pygame.image.load('C:\\Users\\Ben\\Documents\\sprite.png').convert_alpha()
class Background(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.img = pygame.image.load('C:\\Users\\Ben\\Documents\\background.png').convert()
self.img2 = pygame.image.load('C:\\Users\\Ben\\Documents\\trees1.png').convert()
self.treesx = 0
self.treesy = 70
self.treesrect = pygame.draw.rect(setDisplay, pygame.Color(0, 0, 255),pygame.Rect(self.treesx, self.treesy, 376, 100))
def draw(self):
self.setDisplay.blit(self.img)
self.setDisplay.blit(self.img2)
def load(self, filename):
self.img = pygame.image.load('C:\\Users\\Ben\\Documents\\background.png').convert_alpha()
self.img2 = pygame.image.load('C:\\Users\\Ben\\Documents\\trees1.png').convert_alpha()
def detectCollision(sprite1, sprite2):
if sprite1.colliderect(sprite2):
print("worked")
player = Player()
background = Background()
def gameLoop():
imgx = 10
imgy = 10
lead_x_change = 0
lead_y_change = 0
move_variable = 5
while True:
pygame.display.flip()
for event in pygame.event.get():
#print (event)
if event.type == QUIT:
pygame.quit()
sys.exit()
setDisplay.blit(background.img, [0, 0])
setDisplay.blit(background.img2, [0, 0])
setDisplay.blit(player.img, [player.imgx, player.imgy])
if player.rect.colliderect(background.treesrect):
print("collided")
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -move_variable
player.x -= 10
elif event.key == pygame.K_UP:
lead_y_change = -move_variable
elif event.key == pygame.K_RIGHT:
player.imgx += 10
player.x += 10
elif event.key == pygame.K_DOWN:
lead_y_change = move_variable
player.y += 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
lead_x_change = 0
elif event.key == pygame.K_UP:
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = 0
print(player.x, player.y)
player.imgx += lead_x_change
player.imgy += lead_y_change
pygame.display.flip()
pygame.display.update()
gameLoop()
#start (0, 71)
#length (376, 71)
#width (0, 168)
I think this may be due to the fact that, in the class Player, self.rect isn't right. Instead try:
self.rect = self.img.get_rect()
also, in your main loop, why are you blit-ing stuff in the event for loop?
Only put the key presses in for event in pygame.event.get()
There are other things that are very wrong in the code.
May I recommend this excellent tutorial for making games with sprites in pygame.
Hey guys I have been trying to move the ball image in a square manner on the screen with pygame. I have tried many times but it does not work. Please see my code below.
import time
import pygame, sys
from pygame.locals import *
pygame.init()
clocks = pygame.time.Clock()
surfaceObject = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Bounce')
mousey,mousex = 0,0
imgx = 10
imgy = 10
pixmove = 60
tiger = [2,2]
movement = 'down'
background = pygame.image.load('bg.jpg').convert()
ball = pygame.image.load('ball.jpg').convert_alpha()
pygame.mixer.music.load('yeah.mp3')
while True:
time.sleep(1)
if movement == 'down':
imgx += pixmove
if imgx < 640:
tiger[0] - tiger[1]
elif movement == 'right':
imgx += pixmove
if imgx < 0:
movement = 'up'
elif movement == 'up':
imgy -= pixmove
if imgy < 0:
movement = 'left'
elif movement == 'left':
imgx -= pixmove
if imgx < 0:
movement = 'down'
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
surfaceObject.blit(background,(mousex,mousey))
surfaceObject.blit(ball,(imgx,imgy))
pygame.mixer.music.play()
pygame.display.update()
clocks.tick(50)
When I run this code the ball moves in a straight way and the ball does not bounce back when it touches the end.
My goal is to rotate the ball in a square manner across the screen. I have tried changing the pixmove variable but it did not solve my problem.
Hope you guys can help me out ..Thanx in advance
Your indentation is totally broken, so I can't say what's going.
However, moving the image in a square fashion is easy. Just create a Rect in which the object should move, and once the object leaves the Rect, change the direction.
Take a look at the following example:
import pygame
from itertools import cycle
pygame.init()
screen = pygame.display.set_mode((300, 300))
# move inside the screen (or any other Rect)
s_r = screen.get_rect()
player = pygame.Rect((100, 100, 50, 50))
timer = pygame.time.Clock()
speed = 5
up, down, left, right = (0, -speed), (0, speed), (-speed, 0), (speed, 0)
dirs = cycle([up, right, down, left])
dir = next(dirs)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise
# move player
player.move_ip(dir)
# if it's outside the screen
if not s_r.contains(player):
# put it back inside
player.clamp_ip(s_r)
# and switch to next direction
dir = next(dirs)
screen.fill(pygame.color.Color('Black'))
pygame.draw.rect(screen, pygame.color.Color('Grey'), player)
pygame.display.flip()
timer.tick(25)
Since we determined that what you actually want to do is for the ball to bounce off the edges, look here :
Why isn't the ball bouncing back?
In summary, what needs to happen is that you need to keep track of the direction the ball is going (in terms of it's vertical and horizontal movement) and change them as you hit a wall.
You seriously want to fix your indenting, as that leads your code to be highly ununderstandable.
If you want to move something, such as a circle, in a square formation, that is pretty easy:
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((1200, 600))
x, y = (100, 100)
dir = 'right'
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
DISPLAYSURF.fill((0, 0, 0))
pygame.draw.circle(DISPLAYSURF, (255, 255, 255), (x, y), 10)
if dir == 'right':
x+=14
if x >= 1100:
dir = 'down'
elif dir == 'down':
y+=14
if y >= 500:
dir = 'left'
elif dir == 'left':
x-=14
if x <= 100:
dir = 'up'
elif dir == 'up':
y-=14
if y <= 100:
dir = 'right'
pygame.display.flip()
this is my game right now but for some reason i keep getting a
PYTHON GAME.py", line 319, in <module>
blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)
File "C:\Python33\lib\site-packages\pygame\sprite.py", line 1515, in spritecollide
if spritecollide(s.rect):
AttributeError: 'Rocket' object has no attribute 'rect'
error. I have no idea why and ive tried alot of stuff to get it to work.
This stupid thing keeps saying i have to much code so i wrote this sentance to take up room
import pygame
import random
"""
Global constants
"""
# Colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
BLUE = ( 0, 0, 255)
BLACK = [ 0, 0, 0]
WHITE = [255, 255, 255]
black = [ 0,0,0]
white=[255,255,255]
green = ( 0, 255, 0)
red = ( 255, 0, 0)
BLUE = ( 0, 0, 255)
lightblue= ( 0, 255, 255)
brown =( 97, 66, 12)
yellow =(232,232,74)
grey=(148,148,148)
purple=(124,102,196)
yellow2 =(252,252,0)
yellow3 =(252,252,0)
red2=(255,0,0)
brown2 =(51,32,5)
orange = (255,119,0)
a=random.randrange(0,255,1)
b=random.randrange(0,255,1)
c=random.randrange(0,255,1)
#color=(a,b,c)
score=0
x=50
#game_sound = pygame.mixer.Sound("nunu_nights.wav")
# Screen dimensions
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 700
# This class represents the bar at the bottom that the player controls
class Player(pygame.sprite.Sprite):
""" This class represents the bar at the bottom that the player controls. """
# Set speed vector
change_x = 0
change_y = 0
walls = None
# Constructor function
def __init__(self, x, y):
# Call the parent's constructor
pygame.sprite.Sprite.__init__(self)
# Set height, width
self.image = pygame.Surface([15, 15])
self.image.fill(WHITE)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
def changespeed(self, x, y):
""" Change the speed of the player. """
self.change_x += x
self.change_y += y
def update(self):
""" Update the player position. """
# Move left/right
self.rect.x += self.change_x
# Did this update cause us to hit a wall?
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
# If we are moving right, set our right side to the left side of the item we hit
if self.change_x > 0:
self.rect.right = block.rect.left
else:
# Otherwise if we are moving left, do the opposite.
self.rect.left = block.rect.right
# Move up/down
self.rect.y += self.change_y
# Check and see if we hit anything
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
# Reset our position based on the top/bottom of the object.
if self.change_y > 0:
self.rect.bottom = block.rect.top
else:
self.rect.top = block.rect.bottom
class Wall(pygame.sprite.Sprite):
""" Wall the player can run into. """
def __init__(self, x, y, width, height):
""" Constructor for the wall that the player can run into. """
# Call the parent's constructor
pygame.sprite.Sprite.__init__(self)
# Make a black wall, of the size specified in the parameters
self.image = pygame.Surface([width, height])
self.image.fill(BLACK)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
class Rocket(pygame.sprite.Sprite):
""" Rocket Class. """
x=0
y=0
change_x=0
change_y=0
size=10
color=[255, 0, 0]
def move(self):
self.x+=self.change_x
self.y+=self.change_y
def draw(self,screen):
pygame.draw.circle(screen,self.color,[self.x,self.y], self.size)
# Call this function so the Pygame library can initialize itself
pygame.init()
# Create an 800x600 sized screen
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# Set the title of the window
pygame.display.set_caption('ROCKETS EVERYWHERE!!')
all_sprite_list = pygame.sprite.Group()
# Create an empty array
rocket_list = []
# Loop 50 times and add a rocket in a random x,y position
for i in range(100):
x = random.randrange(0, 1000)
y = random.randrange(0, 700)
rocket_list.append([x, y])
rect_x = 50
rect_y = 50
# Speed and direction of rectangle
rect_change_x = 5
rect_change_y = 5
# This is a font we use to draw text on the screen (size 36)
font = pygame.font.Font(None, 36)
# List to hold all the sprites
all_sprite_list = pygame.sprite.Group()
# Make the walls. (x_pos, y_pos, width, height)
wall_list = pygame.sprite.Group()
wall = Wall(0, 0, 10, 800)
wall_list.add(wall)
all_sprite_list.add(wall)
wall = Wall(10, 0, 1000, 10)
wall_list.add(wall)
all_sprite_list.add(wall)
wall = Wall(990, 0, 10, 800)
wall_list.add(wall)
all_sprite_list.add(wall)
wall = Wall(0, 690, 1000, 10)
wall_list.add(wall)
all_sprite_list.add(wall)
block_list = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()
# Create the player object
player = Player(500, 600)
player.walls = wall_list
for i in range(50):
enemyRocket1 = Rocket()
enemyRocket1.change_x=2
enemyRocket1.change_y=2
enemyRocket1.color=[a,b,c]
enemyRocket1.x=random.randrange(0,1000,1)
enemyRocket1.y=random.randrange(0,700,1)
block_list.add(enemyRocket1)
all_sprites_list.add(enemyRocket1)
'''
enemyRocket2 = Rocket()
enemyRocket2.x=50
enemyRocket2.y=0
enemyRocket2.change_x=0
enemyRocket2.change_y=10
enemyRocket2.color=[a,b,c]
'''
all_sprite_list.add(player)
clock = pygame.time.Clock()
display_instructions = True
instruction_page = 1
done= False
# -------- Instruction Page Loop -----------
while done==False and display_instructions:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
if event.type == pygame.MOUSEBUTTONDOWN:
instruction_page += 1
if instruction_page == 3:
display_instructions = False
# Set the screen background
screen.fill(black)
if instruction_page == 1:
# Draw instructions, page 1
# This could also load an image created in another program.
# That could be both easier and more flexible.
#random.play()
#screen.blit(title_intro, [0,0])
text=font.render("ROCKETS EVERYWHERE!!", True, white)
screen.blit(text, [10, 10])
text=font.render("Click mouse to see the instructions", True, white)
screen.blit(text, [10, 40])
if instruction_page == 2:
# Draw instructions, page 2
text=font.render("The objective of the game is to dodge rockets", True, white)
screen.blit(text, [10, 10])
text=font.render("Use the Arrow keys to move around the screen", True, white)
screen.blit(text, [10, 40])
# Limit to 20 frames per second
clock.tick(20)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
#------------------------
#MAIN PROGRAM LOOP
#------------------------
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Set the speed based on the key pressed
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.changespeed(-14, 0)
elif event.key == pygame.K_RIGHT:
player.changespeed(14, 0)
elif event.key == pygame.K_UP:
player.changespeed(0, -7)
elif event.key == pygame.K_DOWN:
player.changespeed(0, 7)
# Reset speed when key goes up
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.changespeed(14, 0)
elif event.key == pygame.K_RIGHT:
player.changespeed(-14, 0)
elif event.key == pygame.K_UP:
player.changespeed(0, 7)
elif event.key == pygame.K_DOWN:
player.changespeed(0, -7)
all_sprite_list.update()
player.update()
screen.fill(BLACK)
all_sprite_list.draw(screen)
#The score
text=font.render("Score="+str(score), True, white)
screen.blit(text, [10, 10])
a=random.randrange(0,255,1)
b=random.randrange(0,255,1)
c=random.randrange(0,255,1)
color=(a,b,c)
enemyRocket1.move()
enemyRocket1.draw(screen)
blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)
# Check the list of collisions.
for block in blocks_hit_list:
score+=99999999999
if score>x:
x+=100
for i in range(len(rocket_list)):
# Draw the rocket
pygame.draw.circle(screen, WHITE, rocket_list[i], 2)
# Move the rocket down one pixel
rocket_list[i][1] += 10
# If the rocket has moved off the bottom of the screen
if rocket_list[i][1] > 700:
# Reset it just above the top
y = random.randrange(-50, -10)
rocket_list[i][1] = y
# Give it a new x position
x = random.randrange(0, 1000)
rocket_list[i][0] = x
score+=1
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
clock.tick(40)
pygame.quit ()
As the error message suggests, you are trying to access the attribute rect of a Rocket.
Looking at your Rocket class, Rocket objects indeed have no such attribute.
I am trying to create a game where "player_one.png" is controlled by the arrow keys to move around and dodge a bunch of randomly placed "player_two.png" that can move around on their own in random directions on a football field.
I have created a program that displays the field and the two images. I am having difficulty getting "player_two.png" display multiple copies on the field and cannot get them to move.
I also cannot get the "player_one.png" image to move based on the arrow key. I found a program using Sprites that moves a red block in the same way I want my player to move but cannot switch out the sprite with my image.
Here is my initial set-up which displays the field and the two images facing each other.
import pygame
import random
pygame.init()
#colors
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 100, 0)
red = (255, 0, 0)
size = [1000, 500]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Tony's newest game attempt")
#boolean for while loop
done = False
#create clock
clock = pygame.time.Clock()
#declare font
font = pygame.font.Font(None, 25)
player_one = pygame.image.load("player_one.png").convert()
player_one.set_colorkey(white)
player_two = pygame.image.load("player_two.png").convert()
player_two.set_colorkey(white)
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(green)
for x in range(60,940,35):
pygame.draw.line(screen, white, [x, 0], [x, 500], 1)
score = 0
text = font.render("Score:" +str(score), True, black)
screen.blit(text, [0, 0])
screen.blit(player_one, [940, 240])
screen.blit(player_two, [60, 240])
pygame.display.flip()
clock.tick(20)
pygame.quit()
The sprite program that uses a class (something I could not get to work with images) moves the Player sprite using this code: (Please note this is not the entire program).
class Player(pygame.sprite.Sprite):
# Constructor function
def __init__(self, color, x, y):
# Call the parent's constructor
pygame.sprite.Sprite.__init__(self)
# Set height, width
self.image = pygame.Surface([35, 35])
self.image.fill(color)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.x = 930
self.rect.y = 250
def reset_player(self):
self.rect.x = 930
self.rect.y = 250
# Find a new position for the player
def update(self):
self.rect.x += self.change_y
self.rect.y += self.change_x
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.rect.x -= player.rect.width
elif event.key == pygame.K_RIGHT:
player.rect.x += player.rect.width
elif event.key == pygame.K_UP:
player.rect.y -= player.rect.height
elif event.key == pygame.K_DOWN:
player.rect.y += player.rect.height
# -- Draw everything
# Clear screen
screen.fill(green)
for x in range(60,940,35):
pygame.draw.line(screen, white, [x, 0], [x, 500], 1)
# Draw sprites
all_sprites_list.draw(screen)
text = font.render("Score: "+str(score), True, black)
screen.blit(text, [10, 10])
# Flip screen
pygame.display.flip()
# Pause
clock.tick(20)
pygame.quit()
Can someone please help me figure out how to get my image to move the way the sprite does. Or help me display "player_two.png" all over the field and move in random directions. It would be best if the "player_two.png" moved every once every 3 times I hit an arrow key. If this is vague please email me and I can send my code. I need to finish this game in 2 weeks!
Multiple comments on the game -
I don't see where self.change_y is defined. Also, shouldn't the update function be like - self.rect.x += self.change_x instead of self.rect.x += self.change_y?
Also, the main loop should be something like this
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if player.rect.x > 0:
player.rect.x -= player.rect.width
elif event.key == pygame.K_RIGHT:
if player.rect.x < screen_width: # the screen/game width
player.rect.x += player.rect.width
# Something similar for the up & down keys
I would recommend you to look at this question.
I think you have the right idea but aren't executing it well.
Try going to your game loop and when displaying an image, display like so:
gameDisplay.blit(player1, (player1X,player1Y))
This way, you can use a if statement to change playerX and player1Y. Insert the following code under the code that quits pygame:
elif e.type == pygame.KEYDOWN:
if e.key == pygame.K_LEFT:
player1X -= 5
pygame.display.update()
elif e.key == pygame.K_RIGHT:
player1X += 5
pygame.display.update()
The reason this works is because the variable that is defining X and Y are not staic. You can also do the same thing for up and down using:
elif e.key == pygame.K_UP:
or
elif e.key == pygame.K_DOWN: