Pygame point image towards mouse - python

I am trying to get this image 'spaceship' to point towards my mouse on screen, proving to be quite difficult so I would appreciate any help :O Also, would appreciate it if you could help with moving an image towards the cursor, i'm guessing that would be quite similar to rotating towards it..
Heres my code:
import sys, pygame, math;
from pygame.locals import *;
spaceship = ('spaceship.png')
mouse_c = ('crosshair.png')
backg = ('background.jpg')
pygame.init()
screen = pygame.display.set_mode((800, 600))
bk = pygame.image.load(backg).convert_alpha()
mousec = pygame.image.load(mouse_c).convert_alpha()
space_ship = pygame.image.load(spaceship).convert_alpha()
clock = pygame.time.Clock()
pygame.mouse.set_visible(False)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN and event.button == 1:
print("test1")
elif event.type == MOUSEBUTTONDOWN and event.button == 3:
print("test3")
screen.blit(bk, (0, 0))
pos = pygame.mouse.get_pos()
screen.blit(mousec, (pos))
screen.blit(space_ship, (400, 300)) #I need space_ship to rotate towards my cursor
pygame.display.update()

Here:
import sys, pygame, math;
from pygame.locals import *;
spaceship = ('spaceship.png')
mouse_c = ('crosshair.png')
backg = ('background.jpg')
pygame.init()
screen = pygame.display.set_mode((800, 600))
bk = pygame.image.load(backg).convert_alpha()
mousec = pygame.image.load(mouse_c).convert_alpha()
space_ship = pygame.image.load(spaceship).convert_alpha()
clock = pygame.time.Clock()
pygame.mouse.set_visible(False)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN and event.button == 1:
print("test1")
elif event.type == MOUSEBUTTONDOWN and event.button == 3:
print("test3")
screen.blit(bk, (0, 0))
pos = pygame.mouse.get_pos()
screen.blit(mousec, (pos))
angle = 360-math.atan2(pos[1]-300,pos[0]-400)*180/math.pi
rotimage = pygame.transform.rotate(space_ship,angle)
rect = rotimage.get_rect(center=(400,300))
screen.blit(rotimage,rect) #I need space_ship to rotate towards my cursor
pygame.display.update()
First get the angle between the space ship and the mouse, then rotate the image and set the center of the image so the image doesn't move around while rotating.

Related

Pygame: Whenever I exit full-screen window, my pygame window always goes to top right corner [duplicate]

This question already has answers here:
Pygame Display Position
(8 answers)
Closed 11 months ago.
Whenever I exit from my full-screen pygame display and return to normal pygame window dimensions the window always goes to the uppermost right corner of my monitor screen is there a way that I can specify the position of the window
This is my source code:
#Setup Python---------------------------------------------------#
import pygame, sys, random, os
#Constants
WIDTH, HEIGHT = (600,400)
BLACK = (0,0,0)
#Setup pygame/window--------------------------------------------#
mainClock = pygame.time.Clock()
from pygame.locals import *
pygame.init()
pygame.display.set_caption('screen resize')
screen = pygame.display.set_mode((WIDTH, HEIGHT),pygame.RESIZABLE)
#fullscreen
fullscreen = False
#Loop-----------------------------------------------------------#
while True:
#Background-------------------------------------------------#
screen.fill(BLACK)
#Buttons----------------------------------------------------#
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_f:
fullscreen = not fullscreen
if fullscreen:
screen = pygame.display.set_mode((1920, 1080),pygame.FULLSCREEN)
else:
screen = pygame.display.set_mode((WIDTH, HEIGHT),pygame.RESIZABLE)
#Update-----------------------------------------------------#
pygame.display.update()
mainClock.tick(60)
I found the solution by using this code:
from pygame._sdl2.video import Window
window = Window.from_display_module()
window.position = (100,100)
I implemented into my source code like this (represented by the <----):
#Setup Python---------------------------------------------------#
import pygame, sys, random, os
from pygame._sdl2.video import Window <-----
#Constants
WIDTH, HEIGHT = (600,400)
BLACK = (0,0,0)
#Setup pygame/window--------------------------------------------#
mainClock = pygame.time.Clock()
from pygame.locals import *
pygame.init()
pygame.display.set_caption('screen resize')
screen = pygame.display.set_mode((WIDTH, HEIGHT),pygame.RESIZABLE)
#fullscreen
fullscreen = False
#Loop-----------------------------------------------------------#
while True:
#Background-------------------------------------------------#
screen.fill(BLACK)
#Buttons----------------------------------------------------#
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_f:
fullscreen = not fullscreen
if fullscreen:
screen = pygame.display.set_mode((1920, 1080),pygame.FULLSCREEN)
else:
screen = pygame.display.set_mode((WIDTH, HEIGHT),pygame.RESIZABLE)
window = Window.from_display_module() <----
window.position = (100,100) <----
#Update-----------------------------------------------------#
pygame.display.update()
mainClock.tick(60)

How would I go about making clickable text in Pygame? [duplicate]

This question already has an answer here:
How to detect when a rectangular object, image or sprite is clicked
(1 answer)
Closed 2 years ago.
Basically, here is a section of my code in Pygame:
button_text=pygame.font.Font("C:\Windows\Fonts\Another Danger - Demo.otf",35)
textSurface,textRect=text_objects("Start game",button_text)
textRect.center=(105,295)
screen.blit(textSurface,textRect)
This is the text I'd like to turn into a clickable format, so that when someone presses the text, it can run a function, such as running the next thing possible.
Any help would be greatly appreciated.
Thanks.
Get the rect from the surface that font.render returns and use it for collision detection and the blit position.
import sys
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
font = pg.font.Font(None, 30)
text_surface = font.render('text button', True, pg.Color('steelblue3'))
# Use this rect for collision detection with the mouse pos.
button_rect = text_surface.get_rect(topleft=(200, 200))
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if event.type == pg.MOUSEBUTTONDOWN:
if event.button == 1:
# Use event.pos or pg.mouse.get_pos().
if button_rect.collidepoint(event.pos):
print('Button pressed.')
screen.fill((40, 60, 70))
screen.blit(text_surface, button_rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()
PyGame does not have buttons, so what you can do here is get the mouse cursor position when clicking with pygame.mouse.get_pos(). If the mouse cursor position is inside the text then you know the text was selected.
Here is an example:
import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1000, 700))
clock = pygame.time.Clock()
tx, ty = 250, 250
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
mouse = pygame.mouse.get_pos()
if mouse[0]in range (tx, tx + 130) and mouse[1] in range (ty, ty + 20):
print("You clicked on the text.")
myfont = pygame.font.SysFont("Marlett", 35)
textsurface = myfont.render(("Start game"), True, (230, 230, 230))
screen.blit(textsurface,(tx, ty))
pygame.display.update()
clock.tick(60)
In this example, I used tx and ty for sizes but you can use rect, it's the same thing.

How do I check to see if a mouse click is within a circle in pygame?

import pygame
pygame.init()
white = 255,255,255
cyan = 0,255,255
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Circle Click Test')
stop = False
while not stop:
gameDisplay.fill(white)
pygame.draw.circle(gameDisplay,cyan,(400,300),(100))
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
####################################################
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Here I have a circle on the screen, and I would like to check to see if the user
clicked within the circle. I know how to do this with a rectangle, I would assume it would be similar. Thanks for any help, I am quite new to pygame.
here is what I have for rectangles:
import pygame
pygame.init()
white = 255,255,255
cyan = 0,255,255
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Circle Click Test')
rectangle = pygame.Rect(400,300,200,200)
stop = False
while not stop:
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, cyan,rectangle,4)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
click = rectangle.collidepoint(pygame.mouse.get_pos())
if click == 1:
print 'CLICKED!'
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Use the distance formula:
################################################################################
# Imports ######################################################################
################################################################################
from pygame.locals import *
import pygame, sys, math
################################################################################
# Screen Setup #################################################################
################################################################################
pygame.init()
scr = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Box Test')
################################################################################
# Game Loop ####################################################################
################################################################################
while True:
pygame.display.update(); scr.fill((200, 200, 255))
pygame.draw.circle(scr, (0, 0, 0), (400, 300), 100)
x = pygame.mouse.get_pos()[0]
y = pygame.mouse.get_pos()[1]
sqx = (x - 400)**2
sqy = (y - 300)**2
if math.sqrt(sqx + sqy) < 100:
print 'inside'
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
################################################################################
################################################################################
################################################################################
you could sample the pixel like this
detect click on shape pygame
otherwise use pythagoras to get the distance from the centre.
As Malik shows, pythagoras works well for circles, but for general solid colour shapes you can do:
if event.type == pygame.MOUSEBUTTONDOWN:
click = gameDisplay.get_at(pygame.mouse.get_pos()) == cyan
if click == 1:
print 'CLICKED!'

image is bad with python in pygame

I have a program in python:
import sys, random, pygame
from pygame.locals import *
pygame.init()
# Preparing Pygame
size = width, height = 718, 502
screen = pygame.display.set_mode(size)
framerate = pygame.time.Clock()
pygame.display.set_caption('Flappy Cube')
#Peparing background
background_x = 0
background_y = 0
background = pygame.image.load("background.jpg")
#Preparing Cube
cube_x = 100
cube_y = 200
cube_unscaled = pygame.image.load("cube.png")
cube = pygame.transform.smoothscale(cube_unscaled, (64, 64))
#Preparing Tubes
tube_x = 750
tube_y= 300
tube_unscaled = pygame.image.load("tube.png")
tube = pygame.transform.smoothscale(tube_unscaled, (125, 500))
# The main game loop
def exit_game():
sys.exit()
while True:
#Background
screen.blit(background, (background_x,background_y))
background_x = background_x+254.5
screen.blit(cube,(cube_x, cube_y))
#Tube
tube_x = tube_x -.075
screen.blit(tube,(tube_x, tube_y))
# If exit
for event in pygame.event.get():
if event.type == pygame.QUIT: exit_game()
# If Space Key is presed
elif event.type == pygame.KEYDOWN and event.key == K_SPACE:
cube_y = cube_y-10
#If Clicked
elif pygame.mouse.get_pressed()[0]:
cube_y = cube_y-10
framerate.tick(60)
pygame.display.flip()
run_game()
I get this result: http://i.stack.imgur.com/MKYRM.png
I have to boost framerate.tick(60) to framerate.tick(700) it looks a glichy. when I program the gravity the multiple images won't look good.
how can i fix the images been drawn multiple times before the screen updates?
Try:
cube_unscaled = pygame.image.load("cube.png").convert_alpha()
You shouldn't need to boost your FPS in such way, 60 is a good value.
Also, I like better this order for your main loop: check events, draw, update, tick.
I don't think it makes a difference to your problem, but I think it easier to understand that way.
while True:
# If exit
for event in pygame.event.get():
if event.type == pygame.QUIT: exit_game()
# If Space Key is presed
elif event.type == pygame.KEYDOWN and event.key == K_SPACE:
cube_y = cube_y-10
#If Clicked
elif pygame.mouse.get_pressed()[0]:
cube_y = cube_y-10
#Background
screen.blit(background, (background_x,background_y))
background_x = background_x+254.5
screen.blit(cube,(cube_x, cube_y))
#Tube
tube_x = tube_x -.075
screen.blit(tube,(tube_x, tube_y))
pygame.display.flip()
framerate.tick(60)
I fixed it! I just needed to fill the screen with black before "bliting" it.

Pygame how to "place" an image when you press a key

import pygame, random, time
class Game(object):
def main(self, screen):
bg = pygame.image.load('data/bg.png')
select = pygame.image.load('data/select.png')
block1 = pygame.image.load('data/enemy1.png')
clock = pygame.time.Clock()
while 1:
clock.tick(30)
spriteList = []
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
spriteList.append(block1, (0, 0))
mouse = pygame.mouse.get_pos()
print(mouse)
screen.fill((200, 200, 200))
screen.blit(bg, (0, 0))
screen.blit(select, (mouse))
for sprite in spriteList:
screen.blit(sprite[0], sprite[1])
pygame.display.flip()
if __name__ == '__main__':
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
pygame.init()
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Sandbox')
Game().main(screen)
I'm trying to make it so where you move the mouse a box follows it. Then when you click the space key, "place" an image where you pressed space and then leave it there and be able to place another image somewhere else without effecting the first one. I tried using spriteList but I am kind of confused on where to go from here.
And when I run it I get an error saying: .append() takes one argument (2 given)
Add a tuple to your list. Also, store the mouse position, not (0, 0). Change
spriteList.append(block1, (0, 0))
to
spriteList.append((block1, mouse))
Also, you could rewrite
for sprite in spriteList:
screen.blit(sprite[0], sprite[1])
to
for (img, pos) in spriteList:
screen.blit(img, pos)

Categories