im trying to split my code into functions and i want to input my own values for x and y. so the character can move from the inputed values. When i try to do this from the function call, nothing happens.
Any suggestions?
import pygame, sys
from pygame.locals import *
pygame.init()
width,height=(842,595)
screen = pygame.display.set_mode((width,height),0,32)
pygame.display.set_caption("game")
man = pygame.image.load("man.png")
target = pygame.image.load("star.png")
#setting a background image
bgimage= pygame.image.load("background.jpg")
##image for the jupiter object
another_target = pygame.image.load("jupiter.gif")
x = 100
y = height-300
another_targetx = 400
another_targety = 500
#allows movement whilst holding down key.
clock= pygame.time.Clock()
def move(x,y):
movingX =0
movingY =0
speedX =0
speedY=0
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
elif event.type==KEYDOWN:
if event.key ==K_LEFT:
x-=5
elif event.key==K_RIGHT:
x+=5
elif event.key==K_UP:
y-=5
elif event.key==K_DOWN:
y+=5
time_Passed=clock.tick(25)
time_elapsed_seconds=time_Passed/1000.0
distanceX = time_elapsed_seconds*speedX
movingX+=distanceX
distanceY=time_elapsed_seconds*speedY
movingY+=distanceY
x+=movingX
y+=movingY
clock.tick(50)
pygame.display.update()
move(x,y)
screen.blit(bgimage,(0,0))
screen.blit(man, (x,y))
screen.blit( another_target,( another_targetx, another_targety))
screen.blit(target,(200,400))
pygame.display.update()
You have an infinite loop within the command move(x, y). The stuff on the outside of this loop which updates the screen is never reached, so nothing ever appears to happen. Try putting everything after the command definition into the while True loop inside the command.
Related
`from turtle import right
import pyautogui, time, random, pygame
from pygame.locals import *
time.sleep(3)
class Square(pygame.sprite.Sprite):
def __init__(self):
super(Square,self).__init__()
self.surf = pygame.Surface((20,20))
self.surf.fill((255,0,0))
self.rect = self.surf.get_rect()
width,height = 960,540
screen = pygame.display.set_mode((width,height))
cont = True
square1 = Square()
while cont:
time.sleep(0.4)
x,y=random.randrange(int(1920/2-
width/2),int(1920/2+width/2)),random.randrange(int(1080/2-height/2),int(1080/2+height/2))
screen.blit(square1.surf,(x,y))
pyautogui.click(x,y)
for event in pygame.event.get():
if event.type == QUIT:
cont=False
elif event.type == KEYDOWN:
if event.key == K_BACKSPACE:
cont=False
pygame.display.flip()`
Hi, so basically I am new to python, now learning the basic pyautogui usage and tried making this useless 'game' which was supposed to move the cursor to some point and draw a square at this point and everything is working completely fine when screen size is set to (1920,1080), but when I change the size to anything else it just fails, like cursor coordinates and square being drawn coordinates are not compatible. Does anybody have an explanation for this?
This happens because you draw a square in a pygame window that has its coordinates (0,0), but the cursor has the coordinates (0,0) of your entire screen. I solve it, that I draw first square with pygame window coordinates and then I couted shift.
Here is my code example:
while True:
time.sleep(0.4)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
elif event.type == KEYDOWN:
if event.key == K_BACKSPACE:
pygame.quit()
exit()
square1.rect.x = random.randint(0, width - square1.rect.w)
square1.rect.y = random.randint(0, height - square1.rect.h)
pyautogui.click((1920/2 - width/2) + square1.rect.centerx,
(1080/2-height/2) + square1.rect.centery)
screen.blit(square1.surf, square1.rect)
pygame.display.flip()
If you have pygame window size same like your entire size, it works becouse coordinates (0,0) are on the same place.
I hope it will help you, Adam
PS: If you move pygame window it not works, because in counting I presuppose, that pygame screen is in center your entire screen.
I have been looking for a way to make an autoclicker, since I haven't had any experience with clicking/typing in Python via a macro. I wanted the program to be able to detect when I press a button (F1) and start clicking constantly until I press the stop button (F2); unfortunately, my code won't output the cps variable and the x and y variable. I just need to be able to detect that it's working there to move on to my actual clicking.
Basically, I'm asking how to fix the key detection.
Python version: 3.6.5
EDIT: i know it checks for 1 and 2, the f1 was opening a python help screen when pressed- so for now im just doing 1 and 2
import random, pygame, pyautogui, time
loop = 1
on = 0
pygame.init()
while(loop == 1):
key = pygame.key.get_pressed()
if(key[pygame.K_1]):
on = 1
elif(key [pygame.K_2]):
on = 0
if(on == 1):
x,y = pygame.mouse.get_pos()
cps = random.randint(10,20)
print(cps, x,y)
Define a user event and call pygame.time.set_timer with this event as the first argument and pygame will start adding the event to the queue after the specified time interval.
import random
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
CLICK_EVENT = pg.USEREVENT + 1
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_1:
pg.time.set_timer(CLICK_EVENT, 1000) # Start the timer.
elif event.key == pg.K_2:
pg.time.set_timer(CLICK_EVENT, 0) # Stop the timer.
elif event.type == CLICK_EVENT:
print(random.randint(10, 20), pg.mouse.get_pos())
screen.fill(BG_COLOR)
pg.display.flip()
clock.tick(30)
pg.quit()
Your code currently checks for the 1 and 2 number keys.
You want K_F1 and K_F2, not K_1 and K_2, for the function keys.
Hey I've been trying to call the pygame events in a function to reduce the clutter of my code. But I am unable to perform the process due to an error with global variables. Any help would be appreciated.
from pygame.locals import *
import pygame, sys
def color():
screen.fill((85,163,48))
def events():
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
print "left"
#sets the game map variables
tilesize = 100
map_width = 600
map_height = 300
#initialises the game screen setting it up with the game map variables
pygame.init()
screen = pygame.display.set_mode((map_width,map_height))
while True:
color()
events()
pygame.display.update()
If you're unable to access a value locally from within a function, the answer is to simply pass the value into the function. Something simple like this should suffice:
def events(ev_list):
for event in ev_list:
if event.type == QUIT:
pygame.quit()
within your game loop you'd call it with:
event_list = pygame.event.get()
events(event_list)
alternatively (less desirable) you can import a library from within the function or declare a variable global
Okay I'm pretty new to using Pygame, I'm really just playing around with some of the methods and events. So far i pretty much have an image that moves around the pygame frame and bounces off any of the edges of the frame when it hits it. if the image touches the top of the frame it will increase a count variable by 1 which will be displayed on the screen. I then wanted to add a feature whereby if I clicked the image which was moving it would also add one onto the count variable. When i added this code in however (I think because the function operates on a loop), depending how long you hold the mouse down, count increases by a multiple of 8. I want to make it so that no matter how long i hold the mouse down for, the event stored inside the MOUSEBUTTONDOWN handler will only fire once. what am I doing wrong?
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
screen =pygame.display.set_mode((600,400))
ball = pygame.image.load("homers.png")
ball = pygame.transform.scale(ball,(225,200))
x=200
y=100
left = True
up = True
color = 67,143,218
def text_objects(text,font):
text_surface = font.render(text,True, color)
return text_surface,text_surface.get_rect()
def message_display(text,x,y,z):
largeText = pygame.font.Font('freesansbold.ttf',z)
TextSurf,TextRect = text_objects(text,largeText)
TextRect.center = (x,y)
screen.blit(TextSurf,TextRect)
def hi(x,y,p,z):
message_display(x,y,p,z)
count = 0
message_count = str(count)
while True: # main game loop
screen.fill((180,0,0))
screen.blit(ball,(x,y))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
hi(message_count,x,y,140)
hi("How Many Times Has Homer Hit His Head?",300,200,20)
if event.type == pygame.MOUSEBUTTONDOWN:
# Set the x, y postions of the mouse click
if ball.get_rect().collidepoint(x, y):
count = count+1
if event.type == pygame.MOUSEBUTTONUP:
0
if left == True:
x=x-10
if x == -100:
left =False
if left == False:
x=x+10
if x == 450:
left = True
if up == True:
y=y-10
if y == -20:
up =False
count = count+1
message_count = str(count)
hi(message_count,x,y,140)
if up == False:
y=y+10
if y== 230:
up =True
pygame.display.update()
You have to fix the indentation of your code:
while True: # main game loop
screen.fill((180,0,0))
screen.blit(ball,(x,y))
hi(message_count,x,y,140)
hi("How Many Times Has Homer Hit His Head?",300,200,20)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# this has to be part of the for loop
if event.type == pygame.MOUSEBUTTONDOWN:
if ball.get_rect().collidepoint(x, y):
count = count+1
...
I am practicing my pygame skills by making a small project. In it, it will blit a background image to the screen. Afterwards, it will use a list called soldiers, and if the item it takes in the list is 1, it will print a soldier, if it is 0, it will skip a space. When I run the code however, it blits the background, then the sprites, then the sprites disappear. I want my sprites to stay on the screen after the for loop has finished. Here is the for loop section:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(background_img, (0,0))
for i in soldiers:
if i == 1:
screen.blit(sprite_img,(x,y))
x = x + 50
time.sleep(0.5)
pygame.display.update()
elif i == 0:
x = x + 50
time.sleep(0.5)
pygame.display.update()
pygame.display.update()
Here is all my code:
import sys, pygame, time
from pygame.locals import *
pygame.init()
soldiers = [0,1,1,1,1,0,0,1,1,0]
x = 0
y = 50
background_img = pygame.image.load("/home/myname/Desktop/Army Project/images/background.png")
sprite_img = pygame.image.load("/home/myname/Desktop/Army Project/images/sprite.png")
size = background_img.get_size()
rect = background_img.get_rect()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Army Men")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(background_img, (0,0))
for i in soldiers:
if i == 1:
screen.blit(sprite_img,(x,y))
x = x + 50
time.sleep(0.5)
pygame.display.update()
elif i == 0:
x = x + 50
time.sleep(0.5)
pygame.display.update()
pygame.display.update()
Thank you for your time.
There are few issues with your code.
First, the pygame.display.update() is redundant in the for loop. You only need to call it once per frame, in your case it will be twice.
Second, do not use time.sleep() in pygame. This essentially freezes your game. So you cannot do anything in it. If you want some sort of a delay, use a timer.
Third, this line appears twice in your if else construct x = x + 50. You could move it outside of the if else.
Lastly, I think your problem is caused by not reseting the variable x. So they still get blit, but outside of the screen.
The code after fixing:
import sys, pygame, time
from pygame.locals import *
pygame.init()
soldiers = [0,1,1,1,1,0,0,1,1,0]
x = 0
y = 50
background_img = pygame.image.load("/home/myname/Desktop/Army Project/images/background.png")
sprite_img = pygame.image.load("/home/myname/Desktop/Army Project/images/sprite.png")
size = background_img.get_size()
rect = background_img.get_rect()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Army Men")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(background_img, (0,0))
x = 0
for i in soldiers:
if i == 1:
screen.blit(sprite_img,(x,y))
x = x + 50
pygame.display.update()