I really have a basic question with a long awnser needed. Can someone show me how to make a Rect jump? I just need a sample with a rectangle.
I see your question and i think i have made some example code for you, but first i want to tell you how it works. In addition to an Y variable to store your location on the Y axis you want a variable called velocityY. For every frame in the game the Y variable is changed with velocityY like this:
while True:
y += velocityY # <----- Here
manage_window()
for event in pygame.event.get():
handle_event(event)
pygame.display.flip()
When you jump you set velocityY to lets say -10 and that will make your rect fly off into the sky, so we need to add gravity. Here is the long example (The important part is):
import pygame
pygame.init()
window = pygame.display.set_mode((800, 600))
x, y = 300, 400
xVelocity, yVelocity = 0, 0
rect = pygame.Rect(x, y, 200, 200)
groundRect = pygame.Rect(0, 500, 800, 100)
clock = pygame.time.Clock()
white = 255, 255, 255
red = 255, 0, 0
black = 0, 0, 0
blue = 0, 0, 255
while True:
clock.tick(60) # Make sure the game is running at 60 FPS
rect = pygame.Rect(x, y, 200, 200) # Updating our rect to match coordinates
groundRect = pygame.Rect(0, 500, 800, 100) # Creating ground rect
# HERE IS WHAT YOU CARE ABOUT #
yVelocity += 0.2 # Gravity is pulling the rect down
x += xVelocity # Here we update our velocity on the X axis
y += yVelocity # Here we update our velocity on the Y axis
# HERE IS WHAT YOU CARE ABOUT #
if groundRect.colliderect(rect): # Check if the rect is colliding with the ground
y = groundRect.top-rect.height
yVelocity = 0
window.fill(white)
pygame.draw.rect(window, red, rect) # Here we draw the rect
pygame.draw.rect(window, black, rect, 5) # Here we draw the black box around the rect
pygame.draw.rect(window, blue, groundRect) # Here we draw the ground
pygame.draw.rect(window, black, groundRect, 5) # Here we draw the black box around the rect
for event in pygame.event.get(): # Getting events
if event.type == pygame.QUIT: # If someone presses X on the window, then we want to quit
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: # Pressing space will make the cube jump
if y >= 300: # Checking if cube is on the ground and not in the air
yVelocity = -10 # Setting velocity to upwards
pygame.display.flip() # Updating the screen
Related
Not sure if what I am trying to do is wrong or impossible. Here is my code:
import pygame
class Window(object):
def __init__(self, (width, height), color, cap=' '):
self.width = width
self.height = height
self.color = color
self.cap = cap
self.screen = pygame.display.set_mode((self.width, self.height))
def display(self):
self.screen
#screen =
pygame.display.set_caption(self.cap)
self.screen.fill(self.color)
class Ball(object):
def __init__(self, window, (x, y), color, size, thick=None):
self.window = window
self.x = x
self.y = y
self.color = color
self.size = size
self.thick = thick
def draw(self):
pygame.draw.circle(self.window, self.color, (self.x, self.y),
self.size, self.thick)
def main():
black = (0, 0, 0)
white = (255, 255, 255)
screen = Window((600, 600), black, 'Pong')
screen.display()
ball = Ball(screen, (300, 300), white, 5)
ball.draw()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
pygame.quit()
main()
This is the error I get:
Traceback (most recent call last):
File "C:\Users\acmil\Desktop\Team 7\newPongLib.py", line 47, in <module>
main()
File "C:\Users\acmil\Desktop\Team 7\newPongLib.py", line 36, in main
ball.draw()
File "C:\Users\acmil\Desktop\Team 7\newPongLib.py", line 28, in draw
self.size, self.thick)
TypeError: argument 1 must be pygame.Surface, not Window
I don't understand if i make a Window object why it won't draw a ball to the screen. Any help is appreciated.
Change your Ball class to the following:
class Ball(object):
def __init__(self, window, (x, y), color, size, thick=0):
self.window = window
self.x = x
self.y = y
self.color = color
self.size = size
self.thick = thick
def draw(self):
pygame.draw.circle(self.window.screen, self.color, (self.x, self.y),
self.size, self.thick)
I made two modifications to your code.
First, as for the error you were getting, you were passing in a custom Window object that you had defined instead of the pygame's Screen object that pygame was expecting. Check out the documentation on this function here.
Second, your original constructor defined thick=None by default, but that pygame function expects an int, so I changed it to thick=0.
It should work after these two changes. Let me know if you still are having issues!
I'm working on making a game for my programming class using python. I don't know how to give the option to the player again when they lose, or quit the game. I am using python 2.7. This is the code for my game:
import pygame, sys, time, random
from pygame.locals import *
# set up pygame
pygame.init()
mainClock = pygame.time.Clock()
# set up the window
WINDOWWIDTH = 1000
WINDOWHEIGHT = 500
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Dankest Memes')
# set up the colors
PINK = (223, 61, 163)
TEXTCOLOR = (223, 61, 163)
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def terminate():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
font = pygame.font.SysFont(None, 48)
TEXTCOLOR = (255,250,250)
Score=4
# set up fonts
font = pygame.font.SysFont(None, 48)
myscore=4
# set up the block data structure
file = 'score.txt'
player = pygame.Rect(300, 100, 40, 40)
playerImage = pygame.image.load('player.png')
playerStretchedImage = pygame.transform.scale(playerImage, (40, 40))
foodImage = pygame.image.load('meme.png')
foods = []
for i in range(20):
foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
foodCounter = 0
NEWFOOD = 40
baddie = pygame.Rect(300, 100, 40, 40)
baddieImage = pygame.image.load('baddie.png')
baddieStretchedImage = pygame.transform.scale(baddieImage, (40, 40))
baddies = []
for i in range(20):
baddies.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
baddieCounter = 0
NEWBADDIE = 120
# set up keyboard variables
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
MOVESPEED = 6
# set up music
pickUpSound = pygame.mixer.Sound('pickup.wav')
pygame.mixer.music.load('background.mp3')
pygame.mixer.music.play(-1, 0.0)
musicPlaying = True
# show the "Start" screen
drawText('Dankest Memes', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press any key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 50)
drawText('Move with WASD or the arrow keys.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 100)
drawText('Collect green Pepes to get points.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 150)
drawText('Avoid the chickens.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 200)
pygame.display.update()
waitForPlayerToPressKey()
# run the game loop
while True:
# check for the QUIT event
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
# change the keyboard variables
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.key == ord('x'):
player.top = random.randint(0, WINDOWHEIGHT - player.height)
player.left = random.randint(0, WINDOWWIDTH - player.width)
if event.key == ord('m'):
if musicPlaying:
pygame.mixer.music.stop()
else:
pygame.mixer.music.play(-1, 0.0)
musicPlaying = not musicPlaying
if event.type == MOUSEBUTTONUP:
foods.append(pygame.Rect(event.pos[0] - 10, event.pos[1] - 10, 20, 20))
foodCounter += 1
if foodCounter >= NEWFOOD:
# add new food
foodCounter = 0
foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
baddieCounter += 1
if baddieCounter >= NEWBADDIE:
baddieCounter = 0
baddies.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
# draw the pink background onto the surface
windowSurface.fill(PINK)
# move the player
if moveDown and player.bottom < WINDOWHEIGHT:
player.top += MOVESPEED
if moveUp and player.top > 0:
player.top -= MOVESPEED
if moveLeft and player.left > 0:
player.left -= MOVESPEED
if moveRight and player.right < WINDOWWIDTH:
player.right += MOVESPEED
drawText('Score: %s' % (Score), font, windowSurface, 10,0)
# draw the block onto the surface
windowSurface.blit(playerStretchedImage, player)
# check if the block has intersected with any food squares.
for food in foods[:]:
if player.colliderect(food):
foods.remove(food)
Score+=2
if musicPlaying:
pickUpSound.play()
for baddie in baddies[:]:
if player.colliderect(baddie):
baddies.remove(baddie)
Score-=4
if musicPlaying:
pickUpSound.play()
if Score < 0:
drawText('You have lost', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press escape to quit the game', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 50)
drawText('Press any other key to play again', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 100)
pygame.display.update()
waitForPlayerToPressKey()
# draw the food
for food in foods:
windowSurface.blit(foodImage, food)
# draw the baddie
for baddie in baddies:
windowSurface.blit(baddieImage, baddie)
# draw the window onto the screen
pygame.display.update()
mainClock.tick(40)
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
The game is simple. The player moves around, collects food to get points and avoids baddies so they don't lose points. When the score drops below 0, the player loses. I managed to get and end game screen, but I can't make it play again or quit the game after this point.
First of, one suggestion. People will be more likely to help you if you show them what you've tried.
anyhow.
What I would do is wrap your entire game loop in a function. Like so:
def game_loop():
while True:
# check for the QUIT event
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
....
next when ever your game ends(I'm assuming it does have a condition that makes it end), call a game over screen function. In your game over screen function, you could first fill the window with a color, then blit any text to the screen you wan to show the user, such as "Press any key to play again". Then you would check if any key was pressed and if so call the game loop function. You also need to check if the user is trying to close the window.
Then call the game over screen function like so:
#pseudo code
if game_has_ended == True:
game_over_screen()
Just getting started with pygame (python 2.7, win7, i3) and looking at the tutorial here: http://www.pygame.org/docs/tut/intro/intro.html
When I run the code example:
import sys, pygame
pygame.init()
size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load('ball.bmp')
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
...from IDLE or powershell, the game window only updates when the mouse is actively moving over the game window. I was expecting that the ball would simply bounce around on its own. Is this mouse--position related performance due to the way pygame/SDL deal with graphics modes? Is it related to the hardware? Is there a way to improve the performance through the code? I'd like to get the proverbial ball rolling with pygame and this seems... odd. Thank you.
edit:
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
You have the update code INSIDE the function! Move it out like this and it will work.
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
This is part of my code that is not working properly, I have tried to set keys to make the paddle move up and down but I can't figure out what is wrong with my code.
playerOnePosition = (WINDOWHEIGHT - PADDLESIZE) /2
y = 0
moveY = 0
#Creates Rectangles for ball and paddles.
paddle1 = pygame.Rect(PADDLEOFFSET,(playerOnePosition,(y)), LINETHICKNESS,PADDLESIZE)
drawPaddle(paddle2)
clock = pygame.time.Clock()
while True: #main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# mouse movement commands
if (event.type == pygame.KEYDOWN):
if(event.key == pygame.K_DOWN):
moveY = -5
if (event.key == pygame.K_UP):
moveY = 5
if (event.type == pygame.UP):
if(event.key == pygame.K_DOWN):
moveY = 0
if (event.key == pygame.K_UP):
moveY = 0
y += moveY
clock.tick(50)
The error is:
Argument must be rect style object
The line that does not work is this one:
paddle1 = pygame.Rect(PADDLEOFFSET,(playerOnePosition, (y)), LINETHICKNESS,PADDLESIZE)
Rect expects four (or two, or one) parameters:
class pygame.Rect
pygame object for storing rectangular coordinates
Rect(left, top, width, height) -> Rect
Rect((left, top), (width, height)) -> Rect
Rect(object) -> Rect
So you have PADDLEOFFSET of left, LINETHICKNESS for width, PADDLESIZE for height.
But for top you have (playerOnePosition, (y)), which is a tuple, not an integer as Rect expects. Change that to an integer and it will work.
Argument must be rect style object is a generic error message the Rect class raises when the parameters are of the wrong type.
I have this code
import pygame, random, sys
from pygame.locals import *
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0 , 0, 255)
WIDTH = 20
HEIGHT = 20
WIDTH1 = 30
HEIGHT1 = 30
MARGIN = 5
MARGIN1 = 10
array_width = 4
array_height = 8
grid = []
guess1 = 'white'
guess2 = 'yellow'
guess3 = 'blue'
guess4 = 'green'
guess5 = 'red'
guess6 = 'pink'
guess7 = 'purple'
guess8 = 'orange'
loop = ()
computerguess = []
# CREATING RANDOM COLOUR SEQUENCE TO GUESS
for i in range(4):
loop = random.randint(1,8)
if loop == 1:
computerguess.append(guess1)
if loop == 2:
computerguess.append(guess2)
if loop == 3:
computerguess.append(guess3)
if loop == 4:
computerguess.append(guess4)
if loop == 5:
computerguess.append(guess5)
if loop == 6:
computerguess.append(guess6)
if loop == 7:
computerguess.append(guess7)
if loop == 8:
computerguess.append(guess8)
print(computerguess)
for row in range(10):
grid.append([])
for column in range(10):
grid[row].append(0)
colors = [(0, 0, 0) for i in range(array_width * array_height)]
blocks = [False for i in range(array_width * array_height)]
indicator_grid = [[None for column in range(4)] for row in range(8)]
pygame.init()
# Set the HEIGHT and WIDTH of the screen
WINDOW_SIZE = [300, 300]
WINDOW_SIZE2 = [300, 300]
screen = pygame.display.set_mode(WINDOW_SIZE)
screen2 = pygame.display.set_mode(WINDOW_SIZE2)
# Set title of screen
pygame.display.set_caption("MASTERMIND GAME")
done = False
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
#TEXT BOX VARIABLES AND DATA
base_font = pygame.font.Font(None, 20)
user_text = ""
input_rect = pygame.Rect (10,250,100,50)
color_active = pygame.Color('lightskyblue3')
color_passive = pygame.Color('gray15')
color=color_passive
active = False
current_color = "white"
grid = [[current_color for column in range(4)] for row in range(8)]
#----MAIN PROGRAM LOOP----#
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
column = pos[0] // (WIDTH + MARGIN)
row = pos[1] // (HEIGHT + MARGIN)
# check if column and row are valid grid indices
if 0 <= row < array_height and 0 <= column < array_width:
try:
grid[row][column] = current_color
except:
print("invalid color")
# TEXT BOX CREATION AND USAGE
if event.type == pygame.MOUSEBUTTONDOWN:
if input_rect.collidepoint(event.pos):
active = True
else:
active = False
if event.type == pygame.KEYDOWN:
if active == True:
if event.key == pygame.K_BACKSPACE:
user_text = user_text[0:-1]
else:
user_text += event.unicode
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
user_text = user_text
if user_text != "":
current_color = user_text
user_text = ""
if active:
color = color_active
else:
color=color_passive
#TEXT FOR THE GUI TO MAKE IT EASIER FOR THE USER
screen.fill(0)
pygame.draw.rect(screen,color,input_rect,2)
text_surface= base_font.render(user_text,True,(255,255,255))
screen.blit(text_surface, (input_rect.x +5, input_rect.y + 5))
text1 = base_font.render("WORK BOTTOM TO TOP ", True, (0, 50, 255))
text2 = base_font.render('POSSIBLE CHOICES:', True, (250, 0, 0))
text3 = base_font.render('WHITE BLUE RED', True, (0, 128, 0))
text4 = base_font.render('GREEN ORANGE PINK', True, (0,128,0))
text5= base_font.render('PURPLE YELLOW', True, (0, 128, 0))
screen.blit(text1,(140, 200))
screen.blit(text2,(140, 220))
screen.blit(text3,(140, 240))
screen.blit(text4,(140, 260))
screen.blit(text5,(140, 280))
screen.blit(text5,(140, 280))
for row, gridrow in enumerate(grid):
for column, color in enumerate(gridrow):
pygame.draw.rect(screen,
color,
[(MARGIN + WIDTH) * column + MARGIN,
(MARGIN + HEIGHT) * row + MARGIN,
WIDTH,
HEIGHT])
if gridrow == computerguess:
text = base_font.render("Correct, you win!!!!!", True, (255, 128, 0))
screen.blit(text,
(10, 220 ))
x = 100 + (MARGIN + WIDTH) * column + MARGIN
y = (MARGIN + HEIGHT) * row + MARGIN
color = "grey"
pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)
for row, gridrow in enumerate(grid):
if computerguess[0] == gridrow[0]:
color = "red"
pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)
if computerguess[1] == gridrow[1]:
color = "purple"
pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)
if computerguess[2] == gridrow[2]:
color = "red"
pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)
if computerguess[3] == gridrow[3]:
color = "red"
pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)
clock.tick(60)
pygame.display.flip()
pygame.quit()
i would like to add a title screen, that says start in the form of a button and then would transfer them to the code to begin playing, but i'm not very sure how to do it, i have added a new window (WINDOW_SIZE2), but i am not sure where to go from there
Any help is much appreciated
Thanks
The implementation of a button is answered several times. For example Pygame mouse clicking detection, How do I detect if the mouse is hovering over a button? PyGame button class is not displaying the text or changing colour on hover or How can I add an image or icon to a button rectangle in Pygame? and myn more.
Create 2 scenes with 2 application loops. The first loop shows the title screen and waits for button 2 to be pressed. The 2nd loop is the game loop:
button_rect = pygame.Rect(x, y, width, height) # start button rectangle
abort = False
start = False
while not abort and not start:
for event in pygame.event.get():
if event.type == pygame.QUIT:
abort = True
if event.type == MOUSEBUTTONDOWN:
if button_rect.collidepoint(event.pos):
start = True
# draw title screen
# [...]
done = abort
while not done:
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# game
# [...]
Alternatively, you can combine both scenes in one loop.Add a variable game_state, implement event handling and draw the scenes depending on the value of game_state. Change the game_state when the start button is pressed:
game_state = 'title'
done = False
while not done:
# event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if game_state == 'title':
if event.type == MOUSEBUTTONDOWN:
if button_rect.collidepoint(event.pos):
game_state = 'game'
elif game_state == 'game':
# handle game events:
# [...]
# drawing
if game_state == 'title':
# draw title screen
# [...]
elif game_state == 'game':
# game
# [...]