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
I am new to c++ and Opencv.
I am trying to detect the mouse coordinates when I click the left button of the mouse, and if such coordinates are within a certain area of the image, it draws a rectangle using the current mouse coordinates as the top-left vertex.
Here is the implementation:
void CallBackFunc(int event, int x, int y, int flags, void * userdata)
{
if(event == EVENT_LBUTTONDOWN || event == EVENT_LBUTTONUP)
{
mouseX=x;
mouseY = y;
`
if(( mouseX >= 0 && mouseX <= 130) && ( mouseY >= 22 && mouseY <=301))
{
rectangle(img,Point(mouseX, mouseY),Point(mouseX+30, mouseY+ 40),Scalar(0,0,0),1,8);
}
}
It will store the coordinates, but it seems that it never executes the inner if statement.
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.MOUSEBUTTONDOWN:
is_inside = my_rect.collidepoint(pygame.mouse.get_pos())
print is_inside
if is_inside == 1:
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("The Penrose Triangle by Roman Formicola", 5, (black))
gameDisplay.blit(label, (300,150))
I had it my goal is that once you click on my_rect the message will stay there indefinately
Just create a variable holding your Rect (actually using the Rect class):
my_rect = pygame.Rect(400, 300, 100, 100)
Then you can use the collidepoint() method of Rect to check if the mouse position is inside my_rect:
...
elif event.type == pygame.MOUSEBUTTONDOWN:
is_inside = my_rect.collidepoint(pygame.mouse.get_pos())
pygame.draw.rect(gameDisplay, cyan, my_rect, 0)
...
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
# [...]
I want to prevent a window from being moved between monitors by checking for the message WM_MOVE and using the SetWindowPos function to keep the window within the bounds of the display. When I try to do this, the window briefly flashes where the mouse is and snaps to a small area on the bottom of the screen. I'm not sure why this is happening, since the code is just like any other collision detection:
case WM_MOVE:
{
int nX = (int)(short)LOWORD(lParam);
int nY = (int)(short)HIWORD(lParam);
if (nX < pDisplayDevice->getLeft()) {
nX = pDisplayDevice->getLeft();
} else if (nX + int(uNormalWidth) > pDisplayDevice->getRight()) {
nX = pDisplayDevice->getRight() - int(uNormalWidth);
}
if (nY < pDisplayDevice->getTop()) {
nY = pDisplayDevice->getTop();
} else if (nY + int(uNormalHeight) > pDisplayDevice->getBottom()) {
nY = pDisplayDevice->getBottom() - int(uNormalHeight);
}
SetWindowPos(hWnd, 0, nX, nY, uNormalWidth, uNormalHeight, 0);
}
break;
pDisplayDevice is basically a pointer to a Rect that contains the coordinates of the display, and uNormalWidth/uNormalHeight are the width and height of the window in windowed mode.
WM_MOVE
lParam The x and y coordinates of the upper-left corner of the client
area of the window. The low-order word contains the x-coordinate while
the high-order word contains the y coordinate.
Each time you enter WM_MOUSE, you Move your windows +8 pixels to the right and +30 pixels to the bottom (no menu in my code). That's the Width of the left sizing border and the height of the top sizing border + Title bar.
That move triggers a recursive chain of WM_MOVE processing, eventually ending up with some coords.
What you could do:
1. Follow Jonathan' advice. WM_MOVE is not the message you are looking for, it's WM_WINDOWPOSCHANGING.
2. Use the NON-client coordinates:
int nX = (int)(short)LOWORD(lParam);
int nY = (int)(short)HIWORD(lParam);
RECT rect;
GetWindowRect( hWnd, &rect );
nX = rect.left;
nY = rect.top;
if (nX < pDisplayDevice->getLeft()) {
[...]