How to detect collision to stay within box - python

So how would I be able to keep the green rectangle from getting outside of the box I have provided? If possible without using any classes. I would like to make a small map for levels within the given window so is there any way I can keep the rectangle from slipping through the lines? Or is it possible to force the rectangle to stop moving after hitting a certain point?
import pygame
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
#Functions
def drawSquare(screen, x, y):
pygame.draw.rect(screen, BLACK, [x, y, 21, 21])
pygame.draw.rect(screen, GREEN, [3+x, 3+y, 15, 15])
def drawMap():
pygame.draw.rect(screen, BLACK, [0, 1, 100, 100],5)
pygame.init()
# Set the width and height of the screen [width, height]
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("")
#Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
#Loading pictures
#Variables
# Speed in pixels per frame
x_speed = 0
y_speed = 0
# Current position
x_coord = 10
y_coord = 10
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
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
elif event.type == pygame.KEYDOWN:
# Figure out if it was an arrow key. If so
# adjust speed.
if event.key == pygame.K_LEFT:
x_speed = -3
elif event.key == pygame.K_RIGHT:
x_speed = 3
if x_coord > 200:
x_speed = 0
elif event.key == pygame.K_UP:
y_speed = -3
elif event.key == pygame.K_DOWN:
y_speed = 3
elif event.type == pygame.KEYUP:
# If it is an arrow key, reset vector back to zero
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_speed = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_speed = 0
x_coord = x_coord + x_speed
y_coord = y_coord + y_speed
# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# --- Drawing code should go here
screen.fill(WHITE)
drawSquare(screen, x_coord, y_coord)
drawMap()
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(45)
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()

If I understand your question, you want to keep the square you are drawing within the view bounds. I think this will do it for you (the top two lines are already in your code above, just to show where this would go).
x_coord = x_coord + x_speed
y_coord = y_coord + y_speed
# consider moving these to the top and using them in your drawMap function
map_x = 0
map_y = 1
map_width = 100
map_height = 100
x_coord = max(map_x, x_coord)
y_coord = max(map_y, y_coord)
# coordinates must be less than size of container
# the 21 here is the size of the square you are drawing
# consider making it a variable rather than hard coded number
x_coord = min(x_coord, map_width - 21)
y_coord = min(y_coord, map_heigh - 21)
While I think if you keep on this course (avoiding using classes/using global variables) you will find your code will become unmaintainable.

Related

Can someone help implement gravity and running animation into my pygame code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm making Mario with pygame for my class assessment this school term and am sorta new to pygame, i can't find anywhere how to properly implement gravity into my game, so when mario jumps, he comes back down. My second problem is trying to make a running animation, i want Mario to flick through pictures as he moves left and right in the order; 1, 2, 3, 2 (and over and over). If someone could help it would be great!
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
mario_width = 55
blue = (77, 240, 255)
green = (0, 186, 43)
ground_colour = (186, 150, 97)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Super Italiano Bros")
direction = 'right'
clock = pygame.time.Clock()
cloudImg = pygame.image.load('Cloud.png')
rightMarioImg = pygame.image.load('MarioRight.png')
rightMarioImg2 = pygame.image.load("MarioRight2.png")
rightMarioImg3 = pygame.image.load("MarioRight3.png")
leftMarioImg = pygame.image.load('MarioLeft.png')
leftMarioImg2 = pygame.image.load('MarioLeft2.png')
leftMarioImg3 = pygame.image.load('MarioLeft3.png')
def marioRight(x,y):
gameDisplay.blit(rightMarioImg, (x,y))
def marioLeft(x,y):
gameDisplay.blit(leftMarioImg, (x,y))
def cloud(x_cloud,y_cloud):
gameDisplay.blit(cloudImg, (x_cloud,y_cloud))
def cloud_two(x_cloud_two,y_cloud_two):
gameDisplay.blit(cloudImg, (x_cloud_two,y_cloud_two))
def game_loop():
global direction
x = (320)
y = (360)
x_cloud = (-200)
y_cloud = (-220)
x_cloud_two = (200)
y_cloud_two = (-170)
x_change = (0)
y_change = (0)
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
print(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
direction = 'left'
if event.key == pygame.K_RIGHT:
x_change = 5
direction = 'right'
if event.key == pygame.K_UP:
y_change = -60
if event.key == pygame.K_ESCAPE:
gameExit = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP:
x_change = 0
y_change = 60
x += x_change
y += y_change
if x <= 0:
x = 0
if y <= 300:
y = 300
if y >= 360:
y = 360
gameDisplay.fill(blue)
pygame.draw.rect(gameDisplay, ground_colour, (0,500,800,500))
pygame.draw.rect(gameDisplay, green, (0, 470, 800, 30))
cloud(x_cloud,y_cloud)
cloud_two(x_cloud_two,y_cloud_two)
if direction == 'right':
marioRight(x,y)
else:
marioLeft(x,y)
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
Fixed some issues and did a lot of code styling. When you press the up key he jumps a fixed amount and when you release it he goes back to the ground level. Now it animates itself. The image is changed every loop, which is probably super fast, so you will probably only want to increase the state every a certain amount of frames.
Summary of what I changed:
Imports are usually grouped in three different blocks (divided by a single blank line) and ordered alphabetically:
The first block contains all standard library imports
The second block contains third party libraries
The third block contains local imports to other files in this project
A file should have 0 not used imports
Function and variable names in python follow snake case notation: my_variable and my_function. "Constants" are written in snake upper case: MY_CONSTANT. Classes use camel case: MyClass.
dicts and lists allow you to store data in a more organized way. For example, we can have a MARIO_IMGS dict of lists that store all the mario images so they can be accessed like MARIO_IMGS['right'][0] (the first image is index 0 as lists start counting by 0).
Try to avoid global variables, I moved the variables that were only needed inside the loop to the game_loop function and the remaining top level statements that were not definitions isnide a if __name__ == '__main__': block that runs whenever this script is launched but not when this scrip is imported.
Functions are meant to be reused, having cloudand cloud_two functions that do exactly the same makes no sense. Call cloud(x_cloud, y_cloud) and then cloud(x_cloud_two, y_cloud_two).
Do not use unneeded brackets if they do not provide clarity, for example: x = (320) should be x = 320
You had a indentation error where you process events outside the event loop, so only the last event would be processed (except for exiting, that part was inside the loop so every event would be checked against pygame.QUIT)
Lines should be 80 chars or lower.
quit() at the end of a python file is not needed. quit() is mostly used to close the python interpreter from a terminal window.
import pygame
# Window width and height in px
DISPLAY_SIZE = (800, 600)
# Window title
TITLE = "Super Italiano Bros"
# Predefined colors
BLUE = (77, 240, 255)
GREEN = (0, 186, 43)
GROUND_COLOR = (186, 150, 97)
# Images
MARIO_IMGS = {
'right': [
pygame.image.load('MarioRight.png'),
pygame.image.load("MarioRight2.png"),
pygame.image.load("MarioRight3.png"),
pygame.image.load("MarioRight2.png"),
],
'left': [
pygame.image.load('MarioLeft.png'),
pygame.image.load('MarioLeft2.png'),
pygame.image.load('MarioLeft3.png'),
pygame.image.load('MarioLeft2.png'),
]
}
CLOUD_IMG = pygame.image.load('Cloud.png')
MAX_STATES = min(map(len, MARIO_IMGS.values())) # 3
def draw_mario(x, y, direction='right', state=0):
screen.blit(MARIO_IMGS[direction][state], (x, y))
def draw_cloud(x_cloud, y_cloud):
screen.blit(CLOUD_IMG, (x_cloud, y_cloud))
def game_loop():
# Mario position
x = 320
y = 360
x_change = 0
state = 0
direction = 'right'
# Cloud positions
x_cloud = -200
y_cloud = -220
x_cloud_two = 200
y_cloud_two = -170
# Clock used to limit the FPS
clock = pygame.time.Clock()
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
print(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
direction = 'left'
if event.key == pygame.K_RIGHT:
x_change = 5
direction = 'right'
if event.key == pygame.K_UP:
y = 300
if event.key == pygame.K_ESCAPE:
game_exit = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
elif event.key == pygame.K_UP:
y = 360
x += x_change
if x < 0:
x = 0
elif x > DISPLAY_SIZE[0]:
x = DISPLAY_SIZE[0]
screen.fill(BLUE)
pygame.draw.rect(screen, GROUND_COLOR, (0, 500, 800, 500))
pygame.draw.rect(screen, GREEN, (0, 470, 800, 30))
draw_cloud(x_cloud, y_cloud)
draw_cloud(x_cloud_two, y_cloud_two)
draw_mario(x, y, direction, state)
# Increase the state to animate Mario
state += 1
state %= MAX_STATES # Start back from 0 if we have reached the end
pygame.display.update()
clock.tick(60)
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode(DISPLAY_SIZE)
pygame.display.set_caption(TITLE)
game_loop()
pygame.quit()
You should probably change your mario and cloud to Sprites. An Sprite is a class that has a rect and an image attributes that define how they are drawn, and then instead of using screen.blit(IMAGE, POSITION) you just tell pygame to draw the sprite and he will use those two attributes to draw the desired image at the position of the rect.

I'm having trouble making the paddles stay in the screen? [duplicate]

This question already has answers here:
Not letting the character move out of the window
(2 answers)
Closed 2 years ago.
I'm trying to make the paddles move up and down : 1 rectangle. moving with w/a/s/d keys 2 rectangle. with arrows. I'm having trouble making the paddles stay in the screen?
You will make two “paddles” (i.e. Rectangles), one on the left side and one on the right side of the screen. These rectangles should be taller than they are wide (i.e. Look like a paddle from a pong game). The paddle on the left should be able to move up and down using the w and s keys, the paddle on the right should move up and down using the up and down arrow keys. Both paddles should not be allowed to leave the top or bottom of the screen. (* for this assignment you are just creating the paddles and getting them moving properly,, no balls necessary). Try to avoid hardcoded values.
# import the necessary modules
import pygame
import sys
#initialize pygame
pygame.init()
# set the size for the surface (screen)
screen_h = 800
screen_w = 600
screen = pygame.display.set_mode((screen_h,screen_w),0)
# set the caption for the screen
pygame.display.set_caption("Template")
# define colours you will be using
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
YELLOW = (255,255,0)
#initialize variables for player
#variables for first rectangle
R1x = 740
R1y = 300
R1w = 50
R1h = 132
R1dx = 0
R1dy = 0
#variables for second rectangle
R2x = 10
R2y = 300
R2w = 50
R2h = 132
R2dx = 0
R2dy = 0
#speed
speed = 3
screen.fill(BLACK)
# set main loop to True so it will run
main = True
# main loop
while main:
for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
main = False # set the "main" variable to False to exit while loop
if event.type ==pygame.KEYDOWN:
if event.key == pygame.K_UP:
R1dx = 0
R1dy = -speed
elif event.key == pygame.K_DOWN:
R1dx = 0
R1dy = speed
if event.key == pygame.K_w:
R2dx = 0
R2dy = -speed
elif event.key == pygame.K_s:
R2dx = 0
R2dy = speed
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
R1dx = 0
R1dy = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
R2dx = 0
R2dy = 0
# move the x and y positions of the rectangles
oldR1x = R1x
oldR1y = R1y
R1x = R1x + R1dx
R1y = R1y + R1dy
if R1x >= screen_w-50:
R1x = oldR1x
R1y = oldR1y
if R1x<= 50:
R1x = oldR1x
R1y = oldR1y
if R1y>= screen_h-50:
R1x = oldR1x
R1y = oldR1y
if R1y<= 50:
R1x = oldR1x
R1y = oldR1y
# draw the shapes, in this case the blue rectangles
pygame.draw.rect(screen, WHITE,(R1x, R1y, R1w, R1h),0)
pygame.draw.rect(screen, WHITE,(R2x, R2y, R2w, R2h),0)
# we are using .flip() here, it basically works the same as .update()
# we will discuss this more in class (you can use either one)
pygame.display.flip()
# quit pygame and exit the program (i.e. close everything down)
pygame.quit()
sys.exit()
First of all you have swapped the screen width (screen_w) and the screen height (screen_h). It has to be:
# set the size for the surface (screen)
screen_w = 800
screen_h = 600
screen = pygame.display.set_mode((screen_w,screen_h),0)
The paddles move just up an down, so it sufficient to limit the y coordinate of the pddels to the range [0, screen_h-R1h]. Note, R1y respectively R2y are the top coordinate of the paddles:
R1y = max(0, min(screen_h-R1h, R1y + R1dy))
R2y = max(0, min(screen_h-R2h, R2y + R2dy))
Furthermore, the screen has to be cleared in the main application loop (screen.fill(BLACK)):
while main:
for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
main = False # set the "main" variable to False to exit while loop
if event.type ==pygame.KEYDOWN:
# [...]
# move the x and y positions of the rectangles
R1y = max(0, min(screen_h-R1h, R1y + R1dy))
R2y = max(0, min(screen_h-R2h, R2y + R2dy))
# clear screen
screen.fill(BLACK)
# draw the shapes, in this case the blue rectangles
pygame.draw.rect(screen, WHITE,(R1x, R1y, R1w, R1h),0)
pygame.draw.rect(screen, WHITE,(R2x, R2y, R2w, R2h),0)
# we are using .flip() here, it basically works the same as .update()
# we will discuss this more in class (you can use either one)
pygame.display.flip()
Note, it the paddles would move along the x axis too (left, right), then the restriction of the x coordinate is similar:
R1x = max(0, min(screen_w-R1w, R1x + R1dx))
R2x = max(0, min(screen_w-R2w, R2x + R2dx))

Object moves off screen

import pygame
#Colors, Allways you need colors!!!!
BLACK = ( 0, 0, 0)
GREEN = ( 0, 255, 0)
WHITE = ( 255, 255, 255)
RED = ( 255, 0, 0)
ORANGE = ( 255, 115, 0)
YELLOW = ( 242, 255, 0)
BROWN = ( 115, 87, 39)
PURPLE = ( 298, 0, 247)
GRAY = ( 168, 168, 168)
PINK = ( 255, 0, 234)
BLUE = ( 0, 0 , 255)
pygame.init()
# Screen
screen = pygame.display.set_mode([700,500])
#Name of thewindow
pygame.display.set_caption("Trial to make PONG")
# Any variables!
x_speed = 0
y_speed = 0
x_coord = 10
y_coord = 250
x = 670
y = 250
other_speed = 0
other_speed2 = 0
rect_x = 50
rect_y = 50
rect_change_x = 5
rect_change_y = 5
clock = pygame.time.Clock()
#Sounds,maybe needed?
#Main Loop__________
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# User pressed down on a key
elif event.type == pygame.KEYDOWN:
# Figure out if it was an arrow key. If so
# adjust speed.
if event.key == pygame.K_UP:
y_speed = -5
elif event.key == pygame.K_DOWN:
y_speed = 5
elif event.key == pygame.K_w:
other_speed2 = -5
elif event.key == pygame.K_s:
other_speed2 = 5
# User let up on a key
elif event.type == pygame.KEYUP:
# If it is an arrow key, reset vector back to zero
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_speed = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_speed = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
other_speed2 = 0
# Move the object according to the speed vector.
x_coord += x_speed
y_coord += y_speed
x += x_speed
y += other_speed2
screen.fill(BLACK)
pygame.draw.rect(screen,BLUE,[x_coord,y_coord,20,60])
pygame.draw.rect(screen,YELLOW,[x,y,20,60])
if x > 650 or x < 0:
# Draw the rectangle
pygame.draw.ellipse(screen, BLUE, [rect_x, rect_y, 50, 50])
# Move the rectangle starting point
rect_x += rect_change_x
rect_y += rect_change_y
if rect_x > 650 or rect_x < 0:
rect_change_x = rect_change_x * -1
if rect_y > 450 or rect_y < 0:
rect_change_y = rect_change_y * -1
pygame.display.flip()
clock.tick(60)
pygame.quit()
Ok so I have 2 paddles in this pong game called Blue and yellow rectangle. I can move them but they move off the screen. How do I prevent that. Iv looked online but nothing seems to be working. I thought about putting rectangles around the screen to make a collision point argument where when the Blue/Yellow paddle hit it they won't move any further, but im not sure how to do that with ought ruining the code? Thank you for your help..
You should check to see if it's off the edge of the screen before you change the y coordinate. See
if y_coord + y_speed >= 0 and y_coord + y_speed + 60 <= 500:
y_coord += y_speed
Though as you can see it can get a little confusing to use numbers, which is why you should avoid hard-coding. It's better to have a display_height, display_width, and y_speed variable. Basically, outside of initializing variables, you should only have 0s as numbers. Also, note what happens when you leave out + y_speed in the if statement.
I suggest you start using the Rect class, since it makes handling such cases easy. Also, your code will become cleaner and shorter.
Here's an example of using Rect. Note that I simply use clamp_ip to ensure the player paddles can't leave the screen:
import pygame
BLACK = pygame.color.Color('Black')
YELLOW = pygame.color.Color('Yellow')
BLUE = pygame.color.Color('Blue')
pygame.init()
screen = pygame.display.set_mode([700,500])
screen_rect = screen.get_rect()
pygame.display.set_caption("Trial to make PONG")
blue_rect = pygame.Rect(10, 250, 20, 60)
yellow_rect = pygame.Rect(670, 250, 20, 60)
ball_rect = pygame.Rect(50, 50, 50, 50)
ball_x_speed = 5
ball_y_speed = 5
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# check all pressed keys and move the paddles
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: blue_rect.move_ip(0, -5)
if pressed[pygame.K_DOWN]: blue_rect.move_ip(0, 5)
if pressed[pygame.K_w]: yellow_rect.move_ip(0, -5)
if pressed[pygame.K_s]: yellow_rect.move_ip(0, 5)
# ensure paddles stay on screen
blue_rect.clamp_ip(screen_rect)
yellow_rect.clamp_ip(screen_rect)
# move the ball
ball_rect.move_ip(ball_x_speed, ball_y_speed)
# check if the ball needs to change direction
if ball_rect.x + ball_rect.width > screen_rect.width or ball_rect.x < 0:
ball_x_speed = ball_x_speed * -1
if ball_rect.y + ball_rect.height> screen_rect.height or ball_rect.y < 0:
ball_y_speed = ball_y_speed * -1
# draw everything
screen.fill(BLACK)
pygame.draw.ellipse(screen, BLUE, ball_rect)
pygame.draw.rect(screen,BLUE, blue_rect)
pygame.draw.rect(screen,YELLOW, yellow_rect)
pygame.display.flip()
clock.tick(60)
pygame.quit()
It seems like you're setting the height of the screen to be 500 pixels. Maybe you could check if your paddles are at the limit of the screen before moving them.
newY = y_coord + y_speed
if newY >= 0 and newY + PADDLE_HEIGHT < SCREEN_HEIGHT:
y_coord = newy

Getting an error saying super takes 1 argument but 0 given?

So I am getting an error saying that the super() takes 1 argument but what argument does it want to take??? I really don't know which it's asking for! Can someone help me fix it or at least tell me what's wrong?
import pygame
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
class Me(pygame.sprite.Sprite):
super().__init__()
def __init__(self, color, width, height):
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
you = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()
player = Player(GREEN, 20, 15)
all_sprites_list.add(player)
pygame.init()
# Set the width and height of the screen [width, height]
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Karl's Game")
#Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
#Loading pictures
background_image = pygame.image.load("back.jpg").convert()
#Variables
# Speed in pixels per frame
x_speed = 0
y_speed = 0
# Current position
x_coord = 10
y_coord = 10
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
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
elif event.type == pygame.KEYDOWN:
# Figure out if it was an arrow key. If so
# adjust speed.
if event.key == pygame.K_LEFT:
x_speed = -3
elif event.key == pygame.K_RIGHT:
x_speed = 3
if x_coord > 200:
x_speed = 0
elif event.key == pygame.K_UP:
y_speed = -3
elif event.key == pygame.K_DOWN:
y_speed = 3
elif event.type == pygame.KEYUP:
# If it is an arrow key, reset vector back to zero
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_speed = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_speed = 0
x_coord = x_coord + x_speed
y_coord = y_coord + y_speed
player.rect.x = pos[x_coord]
player.rect.y = pos[y_coord]
# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# --- Drawing code should go here
screen.blit(background_image, [0,0])
drawSquare(screen, x_coord, y_coord)
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(45)
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()
You must move you super() call inside you class init(self): function. It should be the first line iside the method.
Also, the super call should read.
super(Me, self).__init__()

Make an Image move one space with arrow keys in python / pygame

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:

Categories

Resources