Оранжевый только рандомизирует в правой части экрана python

#python #python-3.x #pygame

#python #python-3.x #pygame

Вопрос:

Поэтому каждый раз, когда мой плеер сталкивается с моим orange или мой orange сталкивается с моей платформой, мой orange будет лишь слегка рандомизироваться вправо, я пытаюсь рандомизировать его везде на экране, но это не работает. Я попытался заставить мой оранжевый вернуться на экран, когда он столкнулся с моим плеером или платформой, затем вернуться вниз и повторить шаги снова. Код рандомизатора, который не работает.

 run = True
while run:
[...]

for Orange in oranges:
        Orange.y  = playerman.speed
    for Orange in oranges:
        for Platform in platforms:
            if Orange.rect.colliderect(Platform.rect) or Orange.rect.colliderect(playerman.rect):
                Orange.speed  = 1
                Orange.x = random.randint(Orange.rect.x,Orange.rect.x   Orange.rect.width)
                Orange.y = random.randrange(0, 1   12)
  

Мой полный код

 import pygame
import random
pygame.init()

window = pygame.display.set_mode((700,500 ))
pygame.display.set_caption("Noobs First Game")

BG = pygame.image.load("b_g1.png")

S = pygame.image.load("Score.png")
S = pygame.transform.scale(S,(S.get_width()//10, S.get_height()//10))

C = pygame.mixer.Sound("Crunch.ogg")

SL = pygame.mixer.Sound("Slurp.ogg")


# Playerman
class Player:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.speed = 5
        self.isJump = False
        self.JumpCount = 10
        self.fall = 0
        self.rect = pygame.Rect(x,y,height,width)
        self.right = [pygame.image.load("Player_runright1.png"),
                      pygame.image.load("Player_runright2.png"),
                      pygame.image.load("Player_runright3.png"),
                      pygame.image.load("Player_runright4.png"),
                      pygame.image.load("Player_runright5.png"),
                      pygame.image.load("Player_runright6.png"),
                      pygame.image.load("Player_runright7.png"),
                      pygame.image.load("Player_runright8.png")]
        
        self.left = [pygame.image.load("Player_runleft1.png"),
                      pygame.image.load("Player_runleft2.png"),
                      pygame.image.load("Player_runleft3.png"),
                      pygame.image.load("Player_runleft4.png"),
                      pygame.image.load("Player_runleft5.png"),
                      pygame.image.load("Player_runleft6.png"),
                      pygame.image.load("Player_runleft7.png"),
                      pygame.image.load("Player_runleft8.png")]
        
        self.idle = [pygame.image.load("Player_idle1.png"),
                     pygame.image.load("Player_idle2.png"),
                     pygame.image.load("Player_idle3.png"),
                     pygame.image.load("Player_idle4.png"),
                     pygame.image.load("Player_idle5.png"),
                     pygame.image.load("Player_idle6.png"),
                     pygame.image.load("Player_idle7.png"),
                     pygame.image.load("Player_idle8.png"),]
        
        self.idlel = [pygame.image.load("Player_idlel1.png"),
                      pygame.image.load("Player_idlel2.png"),
                      pygame.image.load("Player_idlel3.png"),
                      pygame.image.load("Player_idlel4.png"),
                      pygame.image.load("Player_idlel5.png"),
                      pygame.image.load("Player_idlel6.png"),
                      pygame.image.load("Player_idlel7.png"),
                      pygame.image.load("Player_idlel8.png")]


        self.jump = [pygame.image.load("Player_jump1.png"),
                     pygame.image.load("Player_jump2.png"),
                     pygame.image.load("Player_jump3.png"),
                     pygame.image.load("Player_jump4.png"),
                     pygame.image.load("Player_jump5.png"),
                     pygame.image.load("Player_jump6.png")]

        self.ljump = [pygame.image.load("Player_leftjump1.png"),
                      pygame.image.load("Player_leftjump2.png"),
                      pygame.image.load("Player_leftjump3.png"),
                      pygame.image.load("Player_leftjump4.png"),
                      pygame.image.load("Player_leftjump5.png"),
                      pygame.image.load("Player_leftjump6.png")]
        self.direction = "ljump"
        self.direction = "jump"
        self.direction = "idlel"
        self.direction = "idle"
        self.direction = "right"
        self.direction = "left"
        self.right = [pygame.transform.scale(image,(image.get_width() 40, image.get_height() 40)) for image in self.right]
        self.left = [pygame.transform.scale(image,(image.get_width() 40, image.get_height() 40)) for image in self.left]
        self.idle = [pygame.transform.scale(image,(image.get_width() 40, image.get_height() 40)) for image in self.idle]
        self.idlel = [pygame.transform.scale(image,(image.get_width() 40, image.get_height() 40)) for image in self.idlel]
        self.jump = [pygame.transform.scale(image,(image.get_width() 40, image.get_height() 40)) for image in self.jump]
        self.ljump = [pygame.transform.scale(image,(image.get_width() 40, image.get_height() 40)) for image in self.ljump]

        self.next_frame_time = 0
        self.fps = 10
        self.clock = pygame.time.Clock()
        self.anim_index = 0
    def get_rect(self):
        self.rect.topleft = (self.x,self.y)
        return self.rect
    def draw(self):
        if self.direction == "right":
            image_list = self.right
        if self.direction == "left":
            image_list = self.left
        if self.direction == "idle":
            image_list = self.idle
        if self.direction == "idlel":
            image_list = self.idlel
        if self.direction == "jump":
            image_list = self.jump
        if self.direction == "ljump":
            image_list = self.ljump
        # is it time to show next frame?
        time_now = pygame.time.get_ticks()
        if (time_now > self.next_frame_time):
            # time till next frame
            inter_time_delay = 1000 // self.fps
            self.next_frame_time = time_now   inter_time_delay
            # show next frame
            self.anim_index  = 1
            if self.anim_index >= len(image_list):
                self.anim_index = 0

        if self.anim_index >= len(image_list):
            self.anim_index = 0
        player_image = image_list[self.anim_index]

        pygame.draw.rect( window, self.color, self.get_rect(), 2 )
        player_image = image_list[self.anim_index]

        player_rect = player_image.get_rect(center = self.get_rect().center)
        player_rect.centerx  = 3
        player_rect.centery -= 13
        window.blit(player_image, player_rect)

        
            
            
        



class Platform:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y =y
        self. width = width
        self.color = color
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x,y,width,height)
        self.grass = pygame.image.load("Grass_1.png")
        self.grass = pygame.transform.scale(self.grass,(self.grass.get_width()-30, self.grass.get_height()-30))
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)

        platform_rect = self.grass.get_rect(center = self.rect.center)
        platform_rect.centerx  = 5
        platform_rect.centery  = 3
        window.blit(self.grass,platform_rect)


class Platform2:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y =y
        self. width = width
        self.color = color
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x,y,width,height)
        self.grass = pygame.image.load("Grass_2.png")
        self.grass = pygame.transform.scale(self.grass,(self.grass.get_width()-25, self.grass.get_height()-25))
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)

        platform2_rect = self.grass.get_rect(center = self.rect.center)
        platform2_rect.centerx  = 0.1
        platform2_rect.centery -= 0
        window.blit(self.grass,platform2_rect)



######## ALL FRUITS


class Orange:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.speed = 5
        self.rect = pygame.Rect(x,y,width,height)
        self.orange = pygame.image.load("Orange_1.png")
        self.orange = pygame.transform.scale(self.orange,(self.orange.get_width()//25, self.orange.get_height()//25))
    def draw(self):
        self.rect.topleft =(self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)


        orange_rect = self.orange.get_rect(center = self.rect.center)
        orange_rect.centerx -= 1
        orange_rect.centery  = 2
        window.blit(self.orange,orange_rect)


        

# Colors for hitbox
white = (255,255,255)


### DRAWing CLASSES
# Drawing Player
playerman = Player(300,255,40,40,white)

#Drawing Platforms
platform1 = Platform(2200,465,35,35.1,white)

# drawing platform2
Platform1 = Platform2(2300,465,35,35.1,white)

# Drawing Orange
orange1 = Orange(-150,200,25,25,white)




### LIST
# Platform List
platforms = [platform1]

# Platform2 list
Platforms = [Platform1]

# Orange list
oranges = [orange1]








# Windows color
def redrawwindow():
    window.fill((0,0,0))
    window.blit(BG,(0,0))

    # for Food
    window.blit(text,textRect)
    
    # Drawing the player the screen
    playerman.draw()
    # Drawing Platform to the screen
    for Platform in platforms:
        Platform.draw()

    # Drawing Platform2 to the screen
    for Platform2 in Platforms:
        Platform2.draw()

    # Drawing Orange to the screen
    for Orange in oranges:
        Orange.draw()



font = pygame.font.Font("freesansbold.ttf",30)
score = 0
text = font.render(" = " str(score),True,(255,255,255))
textRect = text.get_rect()
textRect.center = ((150,40))


platformGroup = pygame.sprite.Group
Level = [
"1                  1",
"1         o        1",
"1                  1",
"1     o   o        1",
"1            o     1",
"1                  1",
"1                  1",
"1                  1",
"1    o             1",
"1                  1",
"1                  1",
"11       11       11",
"22111111122111111122",
"22222222222222222222",]
for iy, row in enumerate(Level):
    for ix, col in enumerate(row):
        if col == "1":
            new_platform = Platform(ix*35, iy*36.4, 35,35.1,(255, 255, 255))
            platforms.append(new_platform)
for iy, row in enumerate(Level):
    for ix, col in enumerate(row):
        if col == "2":
            new_platform2 = Platform2(ix*35, iy*36.3, 35,35.1,(255, 255, 255))
            Platforms.append(new_platform2)
for iy, row in enumerate(Level):
    for ix, col in enumerate(row):
        if col == "2":
            new_platform2 = Platform2(ix*35, iy*36.3, 35,35.1,(255, 255, 255))
            Platforms.append(new_platform2)
# FRUITS
for iy, row in enumerate(Level):
    for ix, col in enumerate(row):
        if col == "o":
            new_orange = Orange(ix*35, iy*60, 25,25,(255, 255, 255))
            oranges.append(new_orange)





x = 10
y = 10
x_change = 0
y_change = 0
old_x = x
old_y = y
fps = (30)
clock = pygame.time.Clock()


run = True
while run:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            
    # orange falling and colliding with platform
    for Orange in oranges:
        Orange.y  = playerman.speed
    for Orange in oranges:
        for Platform in platforms:
            if Orange.rect.colliderect(Platform.rect) or Orange.rect.colliderect(playerman.rect):
                Orange.speed  = 1
                Orange.x = random.randint(Orange.rect.x,Orange.rect.x   Orange.rect.width)
                Orange.y = random.randrange(0, 1   12)

    


    for Orange in oranges:
        for one in range(len(oranges)-1,-1,-1):
            if playerman.rect.colliderect(oranges[one].rect):
                score  = 1
                text = font.render(" = " str(score),True,(255,255,255))
                textRect.center = ((150,40))
                C.play()


                






    
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_d:
                x_change = -7
            if event.key == pygame.K_a:
                x_change = 7

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_d or event.key == pygame.K_a:
                x_change = 0

            x  = x_change
            if x > 500 - playerman.width or x < 0:
                x = old_x

           
    # lets player move
    keys = pygame.key.get_pressed()
    px, py = playerman.x, playerman.y
    if keys[pygame.K_a] and px > playerman.speed:
            px -= playerman.speed
            playerman.direction = "left"
    elif keys[pygame.K_d] and px < 700 - playerman.height - playerman.speed:
        px  = playerman.speed
        playerman.direction = "right"

    else:      
        if playerman.direction == "right":
            playerman.direction = "idle"
        else:
            if playerman.direction == "left":
                playerman.direction = "idlel"
    if keys[pygame.K_w] and py > playerman.speed:
        py -= playerman.speed
    if keys[pygame.K_s] and py <500 - playerman.width - playerman.speed:
        py  = playerman.speed


    # animation for player jump
    if playerman.fall > 0 and keys[pygame.K_SPACE]:
        if keys[pygame.K_d]:
            playerman.direction = "jump"
    else:
        if playerman.direction == "left":
            if keys[pygame.K_SPACE]:
                playerman.direction = "ljump"

    # player colliding with sides of pllatform
    platform_rect_list = [p.rect for p in platforms]
    player_rect = playerman.get_rect()
    player_rect.topleft = (px, py)


    
    playerman.y = py
    if player_rect.collidelist(platform_rect_list) < 0:
        playerman.x = px


  
    # About isJump
    if not playerman.isJump:
        playerman.y  = playerman.fall
        playerman.fall  = 1
        playerman.isJump = False

        # this part lets you jump on platform only the top 
        collide = False
        for Platform in platforms:
            if playerman.get_rect().colliderect(Platform.rect):
                collide = True
                playerman.isJump = False
                playerman.y = Platform.rect.top - playerman.height
                if playerman.rect.right > Platform.rect.left and playerman.rect.left < Platform.rect.left - playerman.width:
                    playerman.x = Platform.rect.left - playerman.width
                if playerman.rect.left < Platform.rect.right and playerman.rect.right > Platform.rect.right   playerman.width:
                    playerman.x = Platform.rect.right
                       
            # colliding with floor      
            if playerman.rect.bottom >= 500:
                collide = True
                playerman.isJump = False
                playerman.Jumpcount = 10
                playerman.y = 500 - playerman.height

        # Jumping
        if collide:
            if keys[pygame.K_SPACE]:
                playerman.isJump = True
            playerman.fall = 0

    # Jump Count

    else:
        if playerman.JumpCount >= 0:
            playerman.y -= (playerman.JumpCount*abs(playerman.JumpCount))*0.3
            playerman.JumpCount -= 1
        else:
            playerman.isJump = False
            playerman.JumpCount = 10

    redrawwindow()
    window.blit(S,(50,0))
    pygame.display.update()
pygame.quit()

  

Ответ №1:

random.randrange работает аналогично range . Размер вашего экрана 700×500. Следовательно, диапазон для координаты x равен [0, 700-Orange.rect.width ], а диапазон для координат y равен [0, 500-Orange.rect.height ]:

 Orange.x = random.randrange(0, 700-Orange.rect.width)
Orange.y = random.randrange(0, 500-Orange.rect.height)