Dabbig02
Dabbig02

Reputation: 43

How to make an rectangle stay on an moving line in python

I'm trying to make the rectangle stay on the moving line. I heard that I would have to make the rectangle move at the same speed as the line. But I'm kinda screwing the speed up, so if anyone knows how I would fix the speed.

import random, time
import pygame, sys
from random import randint
from pygame.locals import *
pygame.init()



#fall sem teiknar veggi lóðrétta og lárétta
def teikna_vegg(x_veggur):
    fjoldi=len(x_veggur)
    for i in range (0,fjoldi):
        pygame.draw.line(DISPLAYSURF, GREEN, (x_veggur[i][0], x_veggur[i][1]),(x_veggur[i][2],x_veggur[i][3]), veggur_breidd)


def haetta(b):      #lokatexti sem kemur þegar forritið er búið
    text = font.render(b, True, WHITE)
    text_rect = text.get_rect()
    text_x = DISPLAYSURF.get_width() / 2 - text_rect.width / 2
    text_y = DISPLAYSURF.get_height() / 2 - text_rect.height / 2
    DISPLAYSURF.blit(text, [text_x, text_y])
    pygame.display.flip()
    time.sleep(5)
    quit()

# setur upp gluggann
DISPLAYSURF = pygame.display.set_mode((400, 400), 0, 32)    #búa til glugga
pygame.display.set_caption('Lokaverkefni')   #nafn á glugga


FPS = 60 # rammar á sek (hraði)
fpsClock = pygame.time.Clock()

# Litir
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0,255,0)
BLUE = ( 0, 0, 255)
YELLOW = (255,255,0)
litur=BLACK

font = pygame.font.Font(None, 36)   # Leturgerðin sem við notum og stærðin er 36



#upphafshnit kassa


kassi_staerd=10
veggur_breidd=10

#hradi á punkt
hradix=0
hradiy= -0.4



hoppa = False
hoppteljari = 0

# upphafshnit geimvera á y ás
gx=random.randrange(0,350)
gx2 = gx+50
gy = 360

x=gx
y=345

x_veggur_speed = -0.4


x_veggur=[[gx,gy,gx2,gy]]



while True: # main game loop
    DISPLAYSURF.fill(RED)
    teikna_vegg(x_veggur)   #Teiknar lárétta veggi
    #hreyfir svarta punktinn
    x+=hradix
    y+=hradiy





        #takkar til að sjtóra kassa
    for event in pygame.event.get(): # event handling loop
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if (event.key == K_LEFT):
                hradix=-1
            elif (event.key == K_RIGHT):
                hradix=1
            elif (event.key == K_SPACE):
                hoppa=True
            elif event.key == K_ESCAPE:
                pygame.qiuit()
                sys.exit()
        elif event.type == KEYUP:
            if (event.key == K_LEFT ):
                hradix=0
            elif (event.key == K_RIGHT ):
                hradix=0
            elif event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()




        #Hoppið (Jump)
    if hoppa==True:      #ef hann er að hoppa
        hoppteljari+=1
        if hoppteljari<20:  #ef teljari er minni en 20
            y-=2                #þá hækkar hann um 2 á skjánum (mínus tala færir hann ofar)
        elif hoppteljari>20 and hoppteljari<24:     # ef teljari er á bilinu 20 - 24
            y+=0            #þá hreyfist hann ekkert er kyrr í smá stund
        elif hoppteljari>24:    # ef teljari er hærri en 24 (þá er hann á leiðinni niður)
            y+=1    #þá færist hann 1 niður



    #hreyfir svarta punktinn
    x+=hradix


    #I think this needs to be changed
    #Athugar hvort að punktur hittir láréttan vegg 
    fjx=len(x_veggur)
    if hoppteljari==0:  #Ef hann er ekki að hoppa þá lækkar hann um 2 ef hann er ekki á vegg
        y +=2   #punktur lækkar
    for i in range (0,fjx):     # fer í gegnum listan með veggjunum
        #   athugar hvort svarti punkturinn sé á vegg
        if y>x_veggur[i][1]-14 and y<x_veggur[i][3]-12 and x>=x_veggur[i][0]-10 and x<=x_veggur[i][2]+1:
            y -=2 #tekur til baka lækkunina sem var gerð 3 línum ofar
            hoppa=False     #Stoppar hoppið ef hann lendir á vegg
            hoppteljari=0   #núllstillir teljarann fyrir hoppið




    #This code also needs to be changed    
    y+=hradiy
    x_veggur[i][1] += x_veggur_speed
    x_veggur[i][3] += x_veggur_speed

    fjx=len(x_veggur)
    if x_veggur[i][1]>20 and x_veggur[i][3]>20:
    
    
        print (hradiy)
    if x_veggur[i][1]<20 and x_veggur[i][3]<20:
        x_veggur[i][0] = random.randrange(0,350)
        x_veggur[i][1] = 400
        x_veggur[i][2] = x_veggur[i][0]+50
        x_veggur[i][3] = 400
        x_veggur_speed -=0.4
    
    
        #print (x_veggur_speed)


    if y>400:
        haetta("GAME OVER")





    pygame.draw.rect(DISPLAYSURF, litur, (x, y, kassi_staerd, kassi_staerd)) #teiknar svarta kassann
    fpsClock.tick(FPS)
    pygame.display.update()

Upvotes: 2

Views: 87

Answers (1)

Rabbid76
Rabbid76

Reputation: 210889

First you have to compute the y-movement of the player:

move_y = 2
if hoppa==True:
    hoppteljari+=1
    if hoppteljari < 20:
        move_y = -2 
    elif hoppteljari>20 and hoppteljari<24:
        move_y = 0
    elif hoppteljari>24:
        move_y = 1

You have to find the y-distance (dy_platform) to the next platform beneath you:

dy_platform = math.inf
for i in range (0,fjx):
    if x_veggur[i][0] <= x + kassi_staerd and x <= x_veggur[i][2]:
        line_top = x_veggur[i][1]
        player_bottom = (y + kassi_staerd)
        dy = line_top - player_bottom
        if -0.001 <= dy < dy_platform:
            dy_platform = dy 

If the distance is less than the sum of the upward movement of the platform and the falling speed of the player, calculate the new position of the player depending on the y-position of the platform:

if dy_platform - move_y + x_veggur_speed <= 0:
    y = y + dy_platform + x_veggur_speed
    hoppa=False
    hoppteljari=0
else:
    y += move_y 

Complete example:

x_veggur_speed = -0.4:

x_veggur_speed = -5:

import random, time
import pygame, sys
from random import randint
from pygame.locals import *
import math
pygame.init()

#fall sem teiknar veggi lóðrétta og lárétta
def teikna_vegg(x_veggur):
    fjoldi=len(x_veggur)
    for i in range (0,fjoldi):
        pygame.draw.line(DISPLAYSURF, GREEN, (x_veggur[i][0], x_veggur[i][1]),(x_veggur[i][2],x_veggur[i][3]), veggur_breidd)


def haetta(b):      #lokatexti sem kemur þegar forritið er búið
    text = font.render(b, True, WHITE)
    text_rect = text.get_rect()
    text_x = DISPLAYSURF.get_width() / 2 - text_rect.width / 2
    text_y = DISPLAYSURF.get_height() / 2 - text_rect.height / 2
    DISPLAYSURF.blit(text, [text_x, text_y])
    pygame.display.flip()
    #time.sleep(5)
    quit()

# setur upp gluggann
DISPLAYSURF = pygame.display.set_mode((400, 400), 0, 32)    #búa til glugga
pygame.display.set_caption('Lokaverkefni')   #nafn á glugga


FPS = 60 # rammar á sek (hraði)
fpsClock = pygame.time.Clock()

# Litir
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0,255,0)
BLUE = ( 0, 0, 255)
YELLOW = (255,255,0)
litur=BLACK

font = pygame.font.Font(None, 36)   # Leturgerðin sem við notum og stærðin er 36


#upphafshnit kassa


kassi_staerd=10
veggur_breidd=10

#hradi á punkt
hradix=0
hradiy= 0



hoppa = False
hoppteljari = 0

# upphafshnit geimvera á y ás
gx=random.randrange(0,350)
gx = 200
gx2 = gx+50
gy = 360

x = gx
y = 345

x_veggur_speed = -0.4
x_veggur=[[gx,gy,gx2,gy]]

while True: # main game loop
    DISPLAYSURF.fill(RED)
    teikna_vegg(x_veggur)   #Teiknar lárétta veggi
    #hreyfir svarta punktinn
   

    #takkar til að sjtóra kassa
    for event in pygame.event.get(): # event handling loop
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if (event.key == K_LEFT):
                hradix=-1
            elif (event.key == K_RIGHT):
                hradix=1
            elif (event.key == K_SPACE):
                hoppa=True
            elif event.key == K_ESCAPE:
                pygame.qiuit()
                sys.exit()
        elif event.type == KEYUP:
            if (event.key == K_LEFT ):
                hradix=0
            elif (event.key == K_RIGHT ):
                hradix=0
            elif event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

    x += hradix

    #I think this needs to be changed
    #Athugar hvort að punktur hittir láréttan vegg 
    fjx=len(x_veggur)
    
    move_y = 2
    if hoppa==True:
        hoppteljari+=1
        if hoppteljari < 20:
            move_y = -2 
        elif hoppteljari>20 and hoppteljari<24:
            move_y = 0
        elif hoppteljari>24:
            move_y = 1
    
    dy_platform = math.inf
    for i in range (0,fjx):
        if x_veggur[i][0] <= x + kassi_staerd and x <= x_veggur[i][2]:
            line_top = x_veggur[i][1]
            player_bottom = (y + kassi_staerd)
            dy = line_top - player_bottom
            if -0.001 <= dy < dy_platform:
                dy_platform = dy 

    if dy_platform - move_y + x_veggur_speed <= 0:
        y = y + dy_platform + x_veggur_speed
        hoppa=False
        hoppteljari=0
    else:
        y += move_y 

    for i in range (0,fjx):     # fer í gegnum listan með veggjunum
        x_veggur[i][1] += x_veggur_speed
        x_veggur[i][3] += x_veggur_speed  
     
    fjx=len(x_veggur)
    if x_veggur[i][1]>20 and x_veggur[i][3]>20:
        pass
    
        #print (hradiy)
    if x_veggur[i][1]<20 and x_veggur[i][3]<20:
        x_veggur[i][0] = random.randrange(0,350)
        x_veggur[i][1] = 400
        x_veggur[i][2] = x_veggur[i][0]+50
        x_veggur[i][3] = 400
        x_veggur_speed -=0.4
    
    
        #print (x_veggur_speed)

    if y>400:
        haetta("GAME OVER")


    pygame.draw.rect(DISPLAYSURF, litur, (x, y, kassi_staerd, kassi_staerd)) #teiknar svarta kassann
    fpsClock.tick(FPS)
    pygame.display.update()

Upvotes: 3

Related Questions