Key Pressing System PyGame - python-3.x

I'm making a basic pong game and want to make a system where a button press makes the paddle goes up or down. I'm fairly new to PyGame and here's my code so far.
import pygame, sys
from pygame.locals import*
def Pong():
pygame.init()
DISPLAY=pygame.display.set_mode((600,400),0,32)
pygame.display.set_caption("Pong")
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
DISPLAY.fill(BLACK)
while True:
def P(b):
pygame.draw.rect(DISPLAY,WHITE,(50,b,50,10))
xx=150
P(xx)
for event in pygame.event.get():
if event.type==KEYUP and event.key==K_W:
P(xx+10)
xx=xx+10
pygame.display.update()
elif event.type==QUIT:
pygame.quit()
sys.exit()

Please read some tutorials and/or docs. This is really basic and if you don't get this right it will bite you later.
Anyway, here's how it could look:
import pygame
pygame.init()
DISPLAY = pygame.display.set_mode((600,400))
paddle = pygame.Rect(0, 0, 10, 50)
paddle.midleft = DISPLAY.get_rect().midleft
speed = 10
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit(0)
keystate = pygame.key.get_pressed()
dy = keystate[pygame.K_s] - keystate[pygame.K_w]
paddle.move_ip(0, dy * speed)
DISPLAY.fill(pygame.Color("black"))
pygame.draw.rect(DISPLAY, pygame.Color("white"), paddle)
pygame.display.update()
clock.tick(30)
That is ok for Pong but I still wouldn't write my game like this. So read some tutorials and maybe try CodeReview if you really want to improve your code.

Related

Pygame gamepad won't run anymore with an Xbox 360 controller and an Ubuntu machine [duplicate]

This code goes into infinite loop. I cant use A button on xbox 360 controller
import pygame
from pygame import joystick
pygame.init()
joystick = pygame.joystick.Joystick(0)
pygame.joystick.init()
print("start")
while True:
if joystick.get_button(0) == 1 :
print("stoped")
break
I cant use A button on xbox 360 controller
Personnaly, I can, so this seems to be possible. You are just missing that pretty much every user input needs to be updated by pygame through pygame.event.get().
From the pygame documentation:
Once the device is initialized the pygame event queue will start receiving events about its input.
So, apparently you need to get the events in the while loop like such to make the joystick work:
import pygame
from pygame.locals import *
pygame.init()
joystick = pygame.joystick.Joystick(0)
while True:
for event in pygame.event.get(): # get the events (update the joystick)
if event.type == QUIT: # allow to click on the X button to close the window
pygame.quit()
exit()
if joystick.get_button(0):
print("stopped")
break
Also,
In the line if joystick.get_button(0) == 1, you don't need to type == 1 because the statement is already True.
You are initializing pygame.joystick twice: through the line pygame.init() and pygame.joystick.init().
You don't need to type from pygame import joystick because you already already have it in the line import pygame.
You can take this as reference and use it in your own way.
import pygame
import sys
pygame.init()
pygame.joystick.init()
clock = pygame.time.Clock()
WIDTH,HEIGHT = 500,500
WHITE = (255,255,255)
BLUE = (0,0,255)
BLUISH = (75,75,255)
YELLOW =(255,255,0)
screen = pygame.display.set_mode((WIDTH,HEIGHT))
smile = pygame.image.load("smile.jpg")
smile = pygame.transform.scale(smile,(WIDTH,HEIGHT))
idle = pygame.image.load("idle.jpg")
idle = pygame.transform.scale(idle,(WIDTH,HEIGHT))
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.JOYBUTTONDOWN:
if event.button == 0: #press A button to smile
screen.fill(WHITE)
screen.blit(smile,(0,0))
pygame.display.update()
clock.tick(10)
elif event.type == pygame.JOYBUTTONUP:
if event.button == 0:
screen.fill(WHITE)
screen.blit(idle,(0,0))
pygame.display.update()
clock.tick(10)

What can I do to make my PyGame window respond?

I am trying to make a window open every time I run my code, but every time I run the code, it shows the window as unresponsive.
My code is as follows:
import os
import time
import sys
pygame.font.init()
WIDTH, HEIGHT = 500, 400
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("EscapeGame")
BG = pygame.transform.scale(pygame.image.load(os.path.join("GameMap1.png")), (WIDTH, HEIGHT))
def main():
fps = 60
clock = pygame.time.Clock()
def redraw_window():
WIN.blit(BG, (0,0))
pygame.display.update()
while True:
clock.tick(fps)
redraw_window()
for event in pygame.event.get():
if event.type == sys.exit:
sys.exit()
input()
main()
I've already tried a few thing with event.get and event.pump, I'm probably missing something very basic. Could someone tell me what else I could try?
Also, I'm new at pygame, so if anyone sees another mistake, please tell me about. I would greatly appreciate it.
The window is unresponsive because you don't handle the events by calling pygame.event.get().
While pygame.event.get() is in your code, it's never executed because
a) it's in a function you never call
b) your code blocks on the input() call
You're code should look like this:
import os
pygame.init()
WIDTH, HEIGHT = 500, 400
def main():
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("EscapeGame")
BG = pygame.transform.scale(pygame.image.load(os.path.join("GameMap1.png")).convert_alpha(), (WIDTH, HEIGHT))
fps = 60
clock = pygame.time.Clock()
while True:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
WIN.blit(BG, (0,0))
pygame.display.flip()
main()

Quit function is not working in pygame

I want the system to exit when I click the "x" on the window of pygame. I want to be able to call the quit_game function whenever I need to. So if the user does quit, it actually quits. I have tried sys exit and pygame.quit(), but I haven't been able to successfully implement those. Right now I just have the quit function built into the intro screen. I am using python 3.4.3. Here is the code.
import math
import random
import time
import pygame
import sys
import glob
pygame.init()
move=0
FPS=60
blue=(0,0,255)
white=(255,255,255)
black=(0,0,0)
green=(0,155,0)
display_width=800
display_height=600
gamedisplay=pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Stacker')
clock=pygame.time.Clock()
speed=2
smallfont=pygame.font.SysFont("Arial",int(display_width/32))
mediumfont=pygame.font.SysFont("Arial",int(display_width/16))
largefont=pygame.font.SysFont("Arial",int(display_width/10))
gamedisplay.fill(green)
block=display_height/12
pygame.display.update()
def quit_game():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
quit()
def intro_screen():
welcome_message = mediumfont.render(str("Welcome to Stacker!!!"), True,black)
gamedisplay.blit(welcome_message,(display_width/4,display_height/40))
how_to_play_1=smallfont.render(str("Your goal is to get to the major prize bar"),True,black)
gamedisplay.blit(how_to_play_1,(display_width/3.619909502,display_height/2))
how_to_play=smallfont.render(str("Press the space bar to stop the shape"),True,black)
gamedisplay.blit(how_to_play,(display_width/3.48583878,display_height/(12/7)))
quit_game()
pygame.display.update()
def middle_block():
pygame.draw.rect(gamedisplay, blue,(display_width/(32/15),display_height-block,block,block))
pygame.display.update()
def left_block():
pygame.draw.rect(gamedisplay, blue,(display_width/(32/13),display_height-block,block,block))
pygame.display.update()
def right_block():
pygame.draw.rect(gamedisplay, blue,(display_width/(32/17),display_height-block,block,block))
pygame.display.update()
def major_screen():
major_message = mediumfont.render(str("Major Prize Here!"), True,black)
gamedisplay.blit(major_message,(display_width/(10/3),display_height/40))
pygame.display.update()
intro_screen()
pygame.time.delay(8000)
gamedisplay.fill(green)
major_screen()
pygame.draw.rect(gamedisplay, blue,(display_width-display_width,display_height/8,display_width,display_height/60))
pygame.draw.rect(gamedisplay, blue,(display_width-display_width,display_height/2.4,display_width,display_height/60))
middle_block()
left_block()
right_block()
pygame.display.update()
Your code has no main game-loop. You may thinks this:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
quit()
Is your game-loop. While that is almost correct, it is missing a key part. A while loop. Your telling Python to loop through every single event that Pygame is tracking. After it finishes looping through the events once, it stops. You want Python to continually loop through the Pygame events, until the window is closed. To do this create a variable to control your loop. Such as running = True or not_quit = True. Next wrap a while-loop around your for-loop using the control variable as your condition. Lastly, if the user closes the window, set your control variable to False.
running = True # our variable to control the loop.
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False # break the loop
pygame.quit()
sys.exit()
quit()
This should allow you to close your window. I should note however that none of the text/shapes your blitting/drawing to the screen will be visible unless inside your game-loop. So you may need to rethink your code a bit.

How do I make sprites move in python/pygame?

I am making kind of like a pong game but I can't seem to make the paddle to move.
So here is the code:
import pygame
pygame.init()
GameDisplay=pygame.display.set_mode([800,600])
pygame.display.set_caption('GAME')
FPS=pygame.time.Clock()
black=(0,0,0)
white=(255,255,255)
GameDisplay.fill(white)
StopProgram=False
class Paddle(pygame.sprite.Sprite):
def __init__(self,image=pygame.image.load('Paddle.png')):
super(Paddle,self).__init__()
self.image=pygame.image.load('Paddle.png')
self.rect=self.image.get_rect()
self.speed=(2,2)
def setPosition(self,x,y):
self.rect.x=x
self.rect.y=y
def move(self,x,y):
self.rect.centerx
self.rect.centery
PaddleGroup=pygame.sprite.Group()
PaddlePlayer1=Paddle()
PaddlePlayer1.setPosition(235,492)
PaddleGroup.add(PaddlePlayer1)
PaddleGroup.draw(GameDisplay)
while not StopProgram:
for event in pygame.event.get():
if event.type==pygame.QUIT:
StopProgram=True
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_LEFT:
PaddlePlayer1.rect.move_ip(-5,0)
pygame.display.flip()
FPS.tick(60)
pygame.quit()
quit()
I hope someone can help me to my solution.(Sorry for bad english.)

Pygame screen flickering

I am quite new to Python and currently trying to make my first game with Pygame. I just started and got a problem. My screen is flickering white (fill colour) to black. I tried to lower the tick (even to 1), but it didn't help (actually, it was flickering less, but still visible a lot). I tried to find any help online, but everywhere "display.update / flip used more than once per cycle" was suggested as a problem and it didn't fix mine.
I am currently running a Fedora 20 box, with Nvidia graphic card (and nouveau drivers), if the issue is connected with this.
My code:
import pygame
from pygame.locals import *
class visualisation(object):
def __init__(self):
pygame.init()
pygame.time.Clock().tick()
self.window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN, 0)
pygame.mouse.set_visible(False)
pygame.display.set_caption('MY GAME')
self.background = pygame.Surface(self.window.get_size())
self.background = self.background.convert()
self.background.fill((250, 250, 250))
self.window.blit(self.background, (0, 0))
pygame.display.update()
if __name__ == '__main__':
running = True
while(running):
arcade = visualisation()
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
pygame.quit()
Thanks a lot in advance :)
You are calling the following functions in a loop:
pygame.init()
pygame.display.set_mode((0, 0), pygame.FULLSCREEN, 0)
If I am not mistaken this creates a new screen variable which is very bad.
You probably wanted to create a new arcade at the start of the game, instead of on each frame.
Try moving it before the loop:
running = True
arcade = visualisation()
while(running):
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False

Resources