Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confused with movement in pygame

I am trying to make a small game in pygame. The player is the left hand red rectangle (if you run it) and I am just trying to make the rocket variable move to the left quickly. Whenever I run the program if I press any key or move my mouse it moves the rocket.

Here is the code:

import pygame,sys,random
pygame.init()
pygame.key.set_repeat(1, 100)
size=width,height=1280,830


screen = pygame.display.set_mode(size)
black = [0, 0, 0]
white = [255, 255, 255]
sky_blue = ((0,255,255))
red = ((255,0,0))
font = pygame.font.SysFont("Arial",14)
rocket=pygame.Rect(1200,350,150,50)
player= pygame.Rect(250,350,250,50)
hull=100
player_speed=100
while True:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()
    elif event.type==pygame.KEYDOWN:
        if event.key == pygame.K_RIGHT:
            player_speed=player_speed+100
        if event.key == pygame.K_LEFT:
            player_speed=player_speed-100
        if event.key == pygame.K_UP:
            player.top=player.top-50
        if event.key == pygame.K_DOWN:
            player.top=player.top+50

    if player_speed>1000:
        player_speed=1000
    if player_speed<100:
        player_speed=100

    if player.top<0:
        player.top=0
    elif player.bottom>height:
        player.bottom=height
    
    #rocket code
    if player.colliderect(rocket):
        hull=hull-100
    if player_speed>99:
        rocket.right=rocket.right-5
    

screen.fill(sky_blue)
pygame.draw.rect(screen,red,player)
pygame.draw.rect(screen,red,rocket)
renderedText = font.render("Speed: "+str(player_speed),1,black)
screen.blit(renderedText, (width/2+50,10))
if hull<1:
    renderedText = font.render("GAME OVER",1,black)
    screen.blit(renderedText, (width/2+500,500))    
pygame.display.flip()
pygame.time.wait(10)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You indentation is incorrect which is causing a logic error.

if player_speed>1000:

...

rocket.right=rocket.right-5

The code between these lines need to be one indent lower. Else this code will only be run when there is a event. Since the for loop will skip execution of any code within if there is no events.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading