В: Как мне сделать коллекционную монету для моей игровой платформы? - PullRequest
0 голосов
/ 09 мая 2020

Я сделал простую платформерную игру, и я хочу узнать, как я могу сделать базовую c систему сбора монет, при которой монеты появляются на моей платформе, и когда я их потребляю, я получаю очки с помощью системы очков вот моя игра, так что жаль: Игра Я смотрел на YouTube, как это сделать, но нет никакого руководства, которое бы это освещало, и я нашел 1, но они не объясняют, как я могу это сделать , это и мой скрипт:

import pygame
import random
import time
pygame.init()


# screen
window = pygame.display.set_mode((500,500))
pygame.display.set_caption("hyeo")
playerx = 350
playery = 250


# player
class player:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.isJump = False
        self.JumpCount = 10
        self.fall = 0
        self.speed = 5
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window, self.color, self.rect)

# enemy class
class enemys:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window, self.color, self.rect)


# FPS
FPS = 60
clock = pygame.time.Clock()

#  Colors
NiceBlue = (46, 196, 187)
NiceGreen = (48, 196, 46)

# define players by name
playerman = player(40,390,30,30, NiceBlue)
enemy1 = enemys(150,390,150,10, NiceGreen)
enemy2 = enemys(350,300,150,10, NiceGreen)
enemy3 = enemys(70,250,150,10, NiceGreen)
enemy4 = enemys(-1000,480,1900,60, NiceGreen)

# put them in a list so we can call all of them at the same time
enemies  = [enemy1,enemy2,enemy3,enemy4]

# Coins my g

# main Loop
runninggame = True
while runninggame:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False



    keys = pygame.key.get_pressed()
    # Right and Left
    if playerman.y < 250:
        playerman.y += 1
        for enemy in enemies:
            enemy.y += playerman.speed

    # FOR DOWN AND UP
    if playerman.y > 450: #somewhere close to the bottom of the screen
        playerman.y -= playerman.fall  #reverse direction
        for enemy in enemies:
            enemy.y -= playerman.fall


    if keys[pygame.K_LEFT]:
        playerman.x -= playerman.speed
        if playerman.x < 100:
            playerman.x += playerman.speed
            for enemy in enemies:
                enemy.x += playerman.speed

    if keys[pygame.K_RIGHT]:
        playerman.x += playerman.speed
        if playerman.x > 400:
            playerman.x -= playerman.speed
            for enemy in enemies:
                enemy.x -= playerman.speed

    if not playerman.isJump:
        playerman.y += playerman.fall
        playerman.fall += 1
        collide = False
        for enemy in enemies:
            if playerman.rect.colliderect(enemy.rect):
                collide = True
                playerman.y = enemy.rect.top - playerman.height +1
                if playerman.rect.right > enemy.rect.left and playerman.rect.left < enemy.rect.left - playerman.width:
                    playerman.x = enemy.rect.left - player.width
                if playerman.rect.left < enemy.rect.right and playerman.rect.right > enemy.rect.right + playerman.width:
                    playerman.x = enemy.rect.right
                break

        if playerman.rect.bottom >= 500:
            collide = True
            playerman.isJump = False
            playerman.JumpCount = 10
            playerman.y = 500 - playerman.height


        if collide:
            if keys[pygame.K_SPACE]:
                playerman.isJump = True
            playerman.fall = 0
    else:
        if playerman.JumpCount > 0:
            playerman.y -= (playerman.JumpCount*abs(playerman.JumpCount))*0.4
            playerman.JumpCount -= 1
        else:
            playerman.isJump = False
            playerman.JumpCount = 10


    window.fill((0,0,0))
    playerman.draw()
    enemy1.draw()
    enemy2.draw()
    enemy3.draw()
    enemy4.draw()
    pygame.display.update()
pygame.quit()



















1 Ответ

2 голосов
/ 09 мая 2020

как сказал @GrahamOrmond, создайте класс монет, на самом деле вы могли бы использовать тот же класс, но это ваше дело, создать новый список и создавать монеты так же, как враги. L oop через них и проверьте наличие if playerman.rect.colliderect(coin.rect):, и если он столкнется, добавьте 1 к счету и удалите его из списка, вы можете использовать del Coin_list[coin_index], чтобы удалить монету (индекс монеты - это то место в списке, где она есть).

Сначала поставьте go, покажите нам, что вы пробовали, и мы поможем


Отлично, выглядит неплохо, я вижу только 2 проблемы,

1) вам нужно перемещать монеты с помощью свитка, это просто, как и враги, но с монетами, я позволю вам сделать это

2) для столкновения вы делаете то же самое как враги, где при столкновении, двигайтесь сверху, что вам не нужно, вы хотите, чтобы он исчез и go через него

для столкновения, есть своего рода продвинутая техника, которую вы должны использовать, и это это l oop через монеты назад

for i in range(len(Coins_list)-1,-1,-1):
    if playerman.rect.colliderect(coin.rect):
        del Coins_list[i]
        score += 1

это потому, что, когда вы удаляете что-то из списка, все перемещается вниз на один, чтобы заполнить его, например, если вы удалите 3-й элемент, 4-й теперь станет 3-й. поэтому, если вы проходите через все из них и удаляете 3-й, когда вы go переходите к 4-му, это фактически 5-й, поскольку 4-й перемещается на 3-й. поэтому вы пропустите один и получите ошибку индекса при попытке получить последний элемент, который переместился на один меньше. Таким образом, обратное означает, что если вы удалите один, те, которые вы уже проверили, будут перемещены, а те, которые вы anet останутся прежними.

Для текста создайте переменную score (как указано выше) и установите он равен 0. текст жестко запрограммирован на 0, поэтому вы хотите, чтобы это был счет, поэтому он изменился

score = 0
text = font.render('Score = ' + str(score), True, NiceOlive)
textRect = text.get_rect()  
textRect.center = (100, 40)

Я также добавил это к столкновению с монетами внизу score+= 1

теперь вы можете заметить, что монеты не исчезают, потому что вы рисуете их по отдельности, вы хотите рисовать их только в том случае, если они есть в списке

    window.fill((0,0,0))
    window.blit(text,textRect)
    for coin in Coins_list:
        coin.draw()

    playerman.draw()
    for enemey in enemies:
        enemy.draw()

вот полный код

import pygame
import random
import time 
pygame.init()



# ------------------------------------------------------------------------------------------VV window screen size
window = pygame.display.set_mode((500,500))
pygame.display.set_caption("DUDE RUFAIDA UGLY ASS HELL")
# ------------------------------------------------------------------------------------------
# --------------------------------------------VV coins class
class coins:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window, NiceOlive, self.rect)

# ------------------------------------------------------------------------------------------



# --------------------------------------VVV player class

# draw the player
class player:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.isJump = False
        self.JumpCount = 10
        self.speed = 5
        self.fall = 0
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window, self.color, self.rect)
# ------------------------------------------------------------------------------------------

# ------------------------------------------VV enemy class

class enemys:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window, self.color, self.rect)
# ------------------------------------------------------------------------------------------

# --------------------------VV frames per sec
# FPS
FPS = 60
clock = pygame.time.Clock()
# ------------------------------------------------------------------------------------------
# ---------VV colors

# COLORS
NiceYellow = (255,255,0)
NiceOlive = (0, 255, 0)
# ------------------------------------------------------------------------------------------

# ----------------------------VV define enemy and players xx,y,height and colors
# define enemy and player class
playerman = player(40,390,30,30, NiceOlive)
enemy1 = enemys(150,390,100,10, NiceYellow)
enemy2 = enemys(300,300,100,10, NiceYellow)
enemy3 = enemys(80,250,100,10, NiceYellow)
enemy4 = enemys(-5000,490,100000,100, NiceYellow)

enemies = [enemy1,enemy2,enemy3,enemy4]
# ------------------------------------------------------------------------------------------


# --------------------------define coins colors and width,heights anD coins LIST
coin1 = coins(250,250,20,20,NiceOlive)
coin2 = coins(350,350,20,20,NiceOlive)
coin3  = coins(300,300,20,20,NiceOlive)
coin4 = coins(150,150,20,20,NiceOlive)
coin5  = coins(50,390,20,20,NiceOlive)
Coins_list = [coin1,coin2,coin3,coin4,coin5]   
# ------------------------------------------------------------------------------------------


# -----------VV scoring 
# display scoring
font = pygame.font.Font('freesansbold.ttf', 32)
score = 0
text = font.render('Score = ' + str(score), True, NiceOlive)
textRect = text.get_rect()  
textRect.center = (100, 40)
# ------------------------------------------------------------------------------------------
# main loop
runninggame = True
while runninggame:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False
# -----------------------Draw the players and coins and enemys
    window.fill((0,0,0))
    window.blit(text,textRect)
    for coin in Coins_list:
        coin.draw()

    playerman.draw()
    for enemy in enemies:
        enemy.draw()

# ------------------------------------------------------------------------------------------

# --------------------------# VV screen movements
    if playerman.y < 250:
        playerman.y += 1
        for enemy in enemies:
            enemy.y += playerman.speed
        for coin in Coins_list:
            coin.y += playerman.speed

    if playerman.y > 450:
        playerman.y -= playerman.fall
        for enemy in enemies:
            enemy.y -= playerman.fall
        for coin in Coins_list:
            coin.y -= playerman.fall

# ------------------------------------------------------------------------------------------
# ----------------------------VV player keys and screen movements
    keys = pygame.key.get_pressed()


    if keys[pygame.K_LEFT]:
        playerman.x -= playerman.speed
        if playerman.x < 100:
            playerman.x += playerman.speed
            for enemy in enemies:
                enemy.x += playerman.speed
            for coin in Coins_list:
                coin.x += playerman.speed



    if keys[pygame.K_RIGHT]:
        playerman.x += playerman.speed
        if playerman.x > 400:
            playerman.x -= playerman.speed
            for enemy in enemies:
                enemy.x -= playerman.speed
            for coin in Coins_list:
                coin.x -= playerman.speed
# ------------------------------------------------------------------------------------------

# ---------------------------collisions with player and enemy
    if not playerman.isJump:
        playerman.y += playerman.fall
        playerman.fall += 1
        collide = False
        for enemy in enemies:
            if playerman.rect.colliderect(enemy.rect):
                collide = True
                playerman.y = enemy.rect.top - playerman.height + 1
                if playerman.rect.right > enemy.rect.left and playerman.rect.left < enemy.rect.left - playerman.width:
                    playerman.x = enemy.rect.left - playerman.width
                if playerman.rect.left < enemy.rect.right and playerman.rect.right > enemy.rect.right + playerman.width:
                    playerman.x = enemy.rect.right
 # ------------------------------------------------------------------------------------------
# ---------------------------------collision with coins and player     
        for i in range(len(Coins_list)-1,-1,-1):
            if playerman.rect.colliderect(Coins_list[i].rect):
                del Coins_list[i]
                score += 1
                text = font.render('Score = ' + str(score), True, NiceOlive)
                textRect = text.get_rect()  
                textRect.center = (100, 40)                
# ------------------------------- here is the problem I said if playerman.rect.colliderect coin1 it should then collide and delete the coin1 from coin list and then it should add it in to the score 1 point 


        if playerman.rect.bottom >= 500:
            collide = True
            playerman.isJump = False
            playerman.JumpCount = 10
            playerman.y = 500 - playerman.height
        if collide:
            if keys[pygame.K_SPACE]:
                playerman.isJump = True
            playerman.fall = 0

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


    pygame.display.update()
pygame.quit()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...