Пигмейская проблема с подсчетом очков / едой яблока, чтобы получить очки - PullRequest
0 голосов
/ 02 мая 2020

Таким образом, в основном я пытался создать базовую c систему подсчета очков и яблоко, которое я могу есть, чтобы заработать очки, но это продолжает происходить --- https://gyazo.com/89ec9b6d8cfd27cf4bb85ceb5738ca9b это не позволит мне съесть яблоки и он продолжает мигать на моем экране, пожалуйста, помогите, я отметил, где оценка и все в коде

import pygame
import time
import random
pygame.init()


window = pygame.display.set_mode((500,500))
pygame.display.set_caption("I am a hacker")


# player class
class players(object):
    def __init__(self,x,y,height,width):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.isJump = False
        self.JumpCount = 10
        self.fall = 0
        self.speed = 5

# enemy class
class enemys(object):
    def __init__(self,cordx,cordy,heights,widths):
        self.cordx = cordx
        self.cordy = cordy
        self.heights = heights
        self.widths = widths


# color blue for player
blue = (32,207,173)

red = (255,0,0)

orange = (207,135,32)


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

display_width = 50
display_height = 50
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)


# -----------------------------------------------------
# scoring and apple varabiles etc
snake_block = 10
snake_speed = 15 
def Your_score(score):
    value = score_font.render("Your Score: " + str(score), True, red)
    window.blit(value, [0, 0])



def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(window, red, [x[0], x[1], snake_block, snake_block])


def message(msg, color):
    mesg = font_style.render(msg, True, color)
    window.blit(mesg, [500 / 6, 500 / 3])


game_over = False
game_close = False

x1 = 500 / 2
y1 = 500 / 2

x1_change = 0
y1_change = 0

snake_List = []
Length_of_snake = 1

foodx = round(random.randrange(0, 500 - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, 500 - snake_block) / 10.0) * 10.0
# ------------------------------------------------------------------------------------------


# Main Loop
playerman = players(50,390,50,50)
enemyman = enemys(190,390,150,10)
runninggame = True
while runninggame:

    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False
# ------------------------------------------------------------------------
# Scoring and Apple System
    if x1 >= 500 or x1 < 0 or y1 >= 500 or y1 < 0:
            game_close = True
            x1 += x1_change
            y1 += y1_change
            window.fill(red)
    pygame.draw.rect(window, red, [foodx, foody, snake_block, snake_block])
    snake_Head = []
    snake_Head.append(x1)
    snake_Head.append(y1)
    snake_List.append(snake_Head)
    if len(snake_List) > Length_of_snake:
        del snake_List[0]
        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, 500 - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, 500 - snake_block) / 10.0) * 10.0
            Length_of_snake += 1
    # ------------------------------------------------------------------------------




    window.fill((0,0,0))
    player = pygame.draw.rect(window,(blue),(playerman.x,playerman.y,playerman.height,playerman.width))
    enemy = pygame.draw.rect(window,(orange),(enemyman.cordx,enemyman.cordy,enemyman.heights,enemyman.widths))

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and playerman.x > playerman.speed:
        playerman.x -= playerman.speed
    if keys[pygame.K_RIGHT] and playerman.x < 500 - playerman.width - playerman.speed:
        playerman.x += playerman.speed

    if not playerman.isJump:

        playerman.y += playerman.fall
        playerman.fall += 1
# ----------------------------------------------------- # enem1 collisio
# both of my 2 enemy squares collisions push me back when ever I Jump on the top of them on there sides but when I jump on the middle of of both of them it seems to work if I just want it so when I jump on both of my squares I just don't get pushed back 
        player.topleft = (playerman.x, playerman.y)
        collide = False
        playerman.isJump = False
        if player.colliderect(enemy):
            collide = True
            playerman.isJump = False
            playerman.y = enemy.top - player.height
            if player.right > enemy.left and  player.left < enemy.left - player.width:
                playerman.x = enemy.left - player.width
            if player.left < enemy.right and  player.right > enemy.right + player.width:
                playerman.x = enemy.right



        if player.bottom >= 500:
            collide = True
            playerman.isJump = False
            playerman.JumpCount = 10
            playerman.y = 500 - player.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.5
            playerman.JumpCount -= 1
        else:
            playerman.JumpCount = 10
            playerman.isJump = False







    pygame.display.update()


pygame.quit()
``

1 Ответ

1 голос
/ 03 мая 2020

Ваша программа - беспорядок. У вас есть змея и еда, но змея не двигается за едой, это первая проблема. Вы также говорите, яблоки, но есть только одно яблоко, другое - ваша змея. Но у вас также есть игрок и враги, и игрок не змея, так что вы не знаете, что здесь происходит, поэтому не совсем уверены, как помочь без дополнительной информации

Но, чтобы исправить мерцание, у вас есть pygame.display.update() 2 раза, с window.fill((0,0,0)) между ними, поэтому вы обновляете экран с помощью яблока, затем очищаете экран, затем обновляете его снова.

Исправить:

удалить pygame.display.update() в

if len(snake_List) > Length_of_snake:
        ...

        pygame.display.update() #delete

        if x1 == foodx and y1 == foody:
            ...

и переместить window.fill((0,0,0)) на первую строку в l oop

runninggame = True
while runninggame:

    window.fill((0,0,0))
    ...
...