简体   繁体   English

为什么如果语句不起作用 Python 和 Pygame

[英]Why is If statement not working Python and Pygame

So I have created my first game and I want to track the high score with shelve.所以我创建了我的第一个游戏,我想用搁置来跟踪高分。 My logic is that I have a global variable called highscore.我的逻辑是我有一个名为 highscore 的全局变量。 At the beginning of the game in game_menu() it is assigned the value that is in the highscore file.在 game_menu() 中的游戏开始时,它被分配了高分文件中的值。 The logic is that if the current score (dodged) is greater than highscore, then the highscore file gets assigned the value of dodged and that is displayed in the game menu.逻辑是,如果当前分数(躲避)大于高分,那么高分文件被分配躲避的值,并显示在游戏菜单中。 This does work for the most part, but even if the dodged variable is smaller than highscore, it still gets assigned to the file.这在大多数情况下确实有效,但即使躲避变量小于高分,它仍然会被分配给文件。 It's like the game is not seeing the If statement.这就像游戏没有看到 If 语句。 Below is the important part of code of the game.下面是游戏代码的重要部分。

d = shelve.open("highscore.txt")
highscore = d["highscore"]
d.close()

best_score(highscore)

Above, we have assign to the global variable the value inside the file and display via best_score上面,我们将文件内的值分配给全局变量并通过 best_score 显示

if dodged > highscore:
    d = shelve.open("highscore.txt")
    d["highscore"] = dodged
    d.close

This is where I think the problem is.这就是我认为问题所在。 It clearly says if dodged is bigger, but even if it's equal or smaller the file gets replaced with the dodged variable.它清楚地表明如果 dodged 更大,但即使它相等或更小,文件也会被 dodged 变量替换。 I even tried putting in ifesle, but nothing works.我什至尝试放入 ifesle,但没有任何效果。

Below is full code of game as requested以下是所要求的游戏的完整代码

import pygame
import time
import random
import shelve

pygame.init()

display_width = 800
display_height = 600

black = (0,0,0)
red = (255,0,0)
dark_red = (200,0,0)
green = (0,255,0)
dark_green = (0,200,0)

awing_width = 95

gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Lonely ship")
clock = pygame.time.Clock()

background = pygame.image.load("space.jpg")

awingImg = pygame.image.load("A-wing.png")
awingImg = pygame.transform.scale(awingImg, (95,119))

asteroidImg  = pygame.image.load("AsteroidPNG.png")
asteroidImg = pygame.transform.scale(asteroidImg, (100,100))

def score(score):
    scoreFont = pygame.font.Font("freesansbold.ttf", 30)
    text = scoreFont.render("Dodged: "+str(score), True, red)
    gameDisplay.blit(text, (10,10))

def best_score(best_score):
    scoreFont = pygame.font.Font("freesansbold.ttf", 30)
    text = scoreFont.render("Highscore: "+str(best_score), True, red)
    gameDisplay.blit(text, (10,10))

def asteroid(asteroidx, asteroidy, asteroidw, asteroidh):
    gameDisplay.blit(asteroidImg, (asteroidx, asteroidy, asteroidw, asteroidh))

def awing(x,y):
    gameDisplay.blit(awingImg, (x,y))

def text_objects(text, font):
    textSurface = font.render(text, True, red)
    return textSurface, textSurface.get_rect()

def button_text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def message_display(text):
    largeText = pygame.font.Font("freesansbold.ttf", 50)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((display_width/2), (display_height/2))
    gameDisplay.blit(TextSurf, TextRect)
    pygame.display.update()
    time.sleep(2)
    pygame.event.clear()
    game_menu()

def outOfBounds():
    message_display("You flew out of bounds!")

def crash():
    message_display("You crashed!")

def win():
    message_display("YOU WIN!!!")

def button(message,x,y,w,h,dc,bc,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x+w > mouse[0] > x and y+h > mouse [1] > y:
        pygame.draw.rect(gameDisplay, bc, (x,y,w,h))
        if click[0] == 1 and action != None:
            if action == "play":
                game_loop()
            elif action == "quit":
                pygame.quit()
                quit()
    else:     
        pygame.draw.rect(gameDisplay, dc, (x,y,w,h))

    smallText = pygame.font.Font("freesansbold.ttf", 20)
    textSurf, textRect = button_text_objects(message, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    gameDisplay.blit(textSurf, textRect)

global highscore

def game_menu():

    intro = True

    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()


        gameDisplay.blit(background, (0,0))


        d = shelve.open("highscore.txt")
        highscore = d["highscore"]
        d.close()

        best_score(highscore)

        largeText = pygame.font.Font("freesansbold.ttf", 50)
        TextSurf, TextRect = text_objects("Lonely Ship", largeText)
        TextRect.center = ((display_width/2), (display_height/2))
        gameDisplay.blit(TextSurf, TextRect)

        button("Play", 200, 400, 100, 50, dark_green,green, "play")
        button("Quit", 500, 400, 100, 50, dark_red,red, "quit")


        pygame.display.update()
        clock.tick(15)

def game_loop():
    x = (display_width * 0.425)
    y = (display_height * 0.75)

    x_change = 0

    asteroid_startx = random.randrange(0, display_width)
    asteroid_starty = -600
    asteroid_speed = 5
    asteroid_width = 100
    asteroid_height = 100

    dodged = 0
    gameExit = False

    while not gameExit:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change += -10
                elif event.key == pygame.K_RIGHT:
                    x_change += 10

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:   
                    x_change += 10
                elif event.key == pygame.K_RIGHT:
                    x_change += -10

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    game_menu()

        x += x_change


        gameDisplay.blit(background, (0,0))

        asteroid(asteroid_startx, asteroid_starty, asteroid_width, asteroid_height)
        asteroid_starty += asteroid_speed
        awing(x,y)
        score(dodged)

        if x > display_width - awing_width or x < 0:
            outOfBounds()

        if asteroid_starty > display_height:
           asteroid_starty = 0 - asteroid_height
           asteroid_startx = random.randrange(0, display_width)
           dodged += 1
           asteroid_speed += 0.5

        if dodged > highscore:
           d = shelve.open("highscore.txt")
           d["highscore"] = dodged
           d.close



        if y < asteroid_starty + asteroid_height:
            print("y crossover")

            if x > asteroid_startx and x < asteroid_startx + asteroid_width or x + awing_width > asteroid_startx and x + awing_width < asteroid_startx + asteroid_width:
                print("x crossover")
                crash()

            if dodged >= 50:
               d = shelve.open("highscore.txt")
               d["highscore"] = 0
               d.close
               win()

        pygame.display.update()
        clock.tick(60)

game_menu()
game_loop()
pygame.quit()
quit()

I think what happens is you're comparing number to string.我认为发生的情况是您将数字与字符串进行比较。 The number is always smaller as described here , if you're using python 2.x.数总是小描述在这里,如果你正在使用Python 2.x版本If you're using 3.x, then this would raise an error.如果您使用的是 3.x,那么这会引发错误。

0 > '0' // false

Thus what you need to do is cast the highscore to int :因此,您需要做的是将highscoreint

highscore = int(d["highscore"])

Or, the other way around - dodged being a string, because in the case where highscore is a string, you'll never go inside the if .或者, dodged - dodged是一个字符串,因为在highscore是一个字符串的情况下,你永远不会进入if

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM