简体   繁体   English

我如何在这个 python 3.0 游戏中添加生命

[英]How do i add lives into this python 3.0 game

I am quite new to python just trying to learn it.我对 python 很陌生,只是想学习它。 I've followed a tutorial on how to make this game and added my own stuff but I cant seem to add lives.我遵循了有关如何制作此游戏的教程并添加了我自己的东西,但我似乎无法添加生命。 I've tried all I know (not a lot).我已经尝试了所有我知道的(不是很多)。 Anyway, all the tutorials I have watched have not worked either and I have been pulling my hair out over it for like 2 days now, so if anyone can help it would be very appreciated.无论如何,我看过的所有教程也没有奏效,我已经把头发拉出来了大约 2 天,所以如果有人能提供帮助,我将不胜感激。

import math
import random

import pygame
from pygame import mixer

# Intialize the pygame
pygame.init( )

# create the screen
screen = pygame.display.set_mode((800, 600))

# Background
background = pygame.image.load('editor.jpg')
opensound = mixer.Sound("ftw.wav")
opensound.play( )

# Sound
mixer.music.load("bg noise.wav")
mixer.music.play(-1)

# Caption and Icon
pygame.display.set_caption("Virus Invader")
icon = pygame.image.load('virus.png')
pygame.display.set_icon(icon)

# Player
playerImg = pygame.image.load('people.png')
playerX = 370
playerY = 480
playerX_change = 0

# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6

for i in range(num_of_enemies):
    enemyImg.append(pygame.image.load('virus.png'))
    enemyX.append(random.randint(0, 736))
    enemyY.append(random.randint(50, 150))
    enemyX_change.append(1)
    enemyY_change.append(40)

# Bullet

# Ready - You can't see the bullet on the screen
# Fire - The bullet is currently moving

bulletImg = pygame.image.load('ligature.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 2
bullet_state = "ready"

# Score

score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)

textX = 10
testY = 10

# Game Over
over_font = pygame.font.Font('freesansbold.ttf', 64)

def Game_start_text():
    over_text = over_font.render("Let the games begin!", True, (64, 64, 64))
    screen.blit(over_text, (200, 250))


def show_score(x, y):
    score = font.render("Score : " + str(score_value), True, (255, 255, 255))
    screen.blit(score, (x, y))


def game_over_text():
    over_text = over_font.render("GAME OVER", True, (255, 255, 255))
    screen.blit(over_text, (200, 250))


def player(x, y):
    screen.blit(playerImg, (x, y))


def enemy(x, y, i):
    screen.blit(enemyImg[i], (x, y))


def fire_bullet(x, y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bulletImg, (x + 16, y + 10))


def isCollision(enemyX, enemyY, bulletX, bulletY):
    distance = math.sqrt(math.pow(enemyX - bulletX, 2) + (math.pow(enemyY - bulletY, 2)))
    if distance < 27:
        return True
    else:
        return False


# Game Loop
running = True
while running:

    # RGB = Red, Green, Blue
    screen.fill((0, 0, 0))
    # Background Image
    screen.blit(background, (0, 0))
    for event in pygame.event.get( ):
        if event.type == pygame.QUIT:
            running = False

        # if keystroke is pressed check if its right or left
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                playerX_change = -2
            if event.key == pygame.K_RIGHT:
                playerX_change = 2
            if event.key == pygame.K_SPACE:
                if bullet_state is "ready":
                    bulletSound = mixer.Sound("stab.wav")
                    bulletSound.play( )
                    # Get the current x cordinate of the charctar
                    bulletX = playerX
                    fire_bullet(bulletX, bulletY)

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerX_change = 0

    # 5 = 5 + -0.1 -> 5 = 5 - 0.1
    # 5 = 5 + 0.1

    playerX += playerX_change
    if playerX <= 0:
        playerX = 0
    elif playerX >= 736:
        playerX = 736

    # Enemy Movement
    for i in range(num_of_enemies):

        # Game Over
        if enemyY[i] > 440:
            for j in range(num_of_enemies):
                enemyY[j] = 2000
            game_over_text( )
            break

        enemyX[i] += enemyX_change[i]
        if enemyX[i] <= 0:
            enemyX_change[i] = 1
            enemyY[i] += enemyY_change[i]
        elif enemyX[i] >= 736:
            enemyX_change[i] = -1
            enemyY[i] += enemyY_change[i]

        # Collision
        collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
        if collision:
            explosionSound = mixer.Sound("street fighter die.wav")
            explosionSound.play( )
            bulletY = 480
            bullet_state = "ready"
            score_value += 1
            enemyX[i] = random.randint(0, 736)
            enemyY[i] = random.randint(50, 150)

        enemy(enemyX[i], enemyY[i], i)

    # Bullet Movement
    if bulletY <= 0:
        bulletY = 480
        bullet_state = "ready"

    if bullet_state is "fire":
        fire_bullet(bulletX, bulletY)
        bulletY -= bulletY_change

    player(playerX, playerY)
    show_score(textX, testY)
    pygame.display.update( )

The reason adding this to your code is so difficult is because there's a whole bunch of extra code that's in the way.将它添加到您的代码中之所以如此困难,是因为有一大堆额外的代码在路上。

When this happens, take a step back, and try to write a skeleton to do just what you need.发生这种情况时,请退后一步,尝试编写一个框架来满足您的需要。 When working on a huge system, say tracking down a complex bug, normally you would comment out sections of the code to pair the problem-space back to something manageable.当在一个庞大的系统上工作时,比如追踪一个复杂的错误,通常你会注释掉代码的一部分,以将问题空间与可管理的东西配对。 Your code is pretty small, so maybe you can just ignore a lot of it.你的代码很小,所以也许你可以忽略很多。

In any event, take a backup of your code, then start adding the changes bit by bit, testing as you go.无论如何,备份您的代码,然后开始一点一点地添加更改,像您一样测试 go。

First add a life-counter:首先添加一个生命计数器:

# Player
playerLives    = 3                                 # <<-- HERE
playerImg      = pygame.image.load('people.png')
playerX        = 370
playerY        = 480
playerX_change = 0

Then some way to test life-loss:然后是一些测试生命损失的方法:

    # if keystroke is pressed check if its right or left
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            playerX_change = -2
        elif event.key == pygame.K_RIGHT:
            playerX_change = 2
        elif event.key == pygame.K_d:   # TEST CODE - Die on 'd'  <<-- HERE
            print( "Player Dies" )
            playerLives -= 1

Now test this?现在测试这个? Did it print "Player Dies" when you press d?当您按 d 时,它是否打印“玩家死亡”?

So... what should happen when the lives is zero?那么......当生命为零时应该发生什么? Maybe the player can't move any more:也许玩家不能再移动了:

# Has the player run out of lives?
if ( playerLives <= 0 ):
    game_over_text()
else:
    # Player still alive, allow controls, draw player
    playerX += playerX_change
    if playerX <= 0:
        playerX = 0
    elif playerX >= 736:
        playerX = 736
    player(playerX, playerY)

Add these next changes in, test them.添加这些下一个更改,测试它们。 Does pressing d three times print "Player Dies" every time, and result in the game_over_text() function being called?是否每次按d三次打印“玩家死亡”,并导致调用game_over_text() function?

Then change the show_score() function to also draw the lives left:然后更改show_score() function 以同样绘制左边的生命:

def show_score(x, y):
    score = font.render("Score : " + str(score_value), True, (255, 255, 255))
    screen.blit(score, (x, y))
    # Write the Lives-left to the right of the score
    lives = font.render("Lives : " + str(playerLives), True, (255, 255, 255))
    screen.blit(lives, (x+200, y))

Test that.测试一下。 Does the on-screen score work?屏幕上的分数是否有效? No?不? Make some small changes, test again, keep tweaking, keep fixing.做一些改动,再次测试,不断调整,不断修复。 If it all goes to hell-in-a-handcart you only need small changes to undo it.如果这一切都变成了手推车中的地狱,您只需要进行小的更改即可撤消它。

Now that the losing-lives mechanism is working, find where it should actually take away lives, and add the changes in:现在失去生命的机制正在工作,找到它实际上应该夺走生命的地方,并添加以下更改:

    # Game Over
    if enemyY[i] > 440:
        for j in range(num_of_enemies):
            enemyY[j] = 2000
        playerLives -= 1           # <<-- lose a life
        #game_over_text( )
        reset_enemy_positions()    # <<-- move enemies back to top, TODO!
        break

Of course if you leave your enemies below line 440, the lose-a-life condition is still true.当然,如果您将敌人留在 440 行以下,则丧命情况仍然成立。 Thus the player will continue to lose many lives per second, every frame update.因此,每帧更新,玩家将继续每秒失去许多生命。 The enemies need to move back to start-position (or some suchlike).敌人需要回到起始位置(或类似的位置)。

Anyway I hope this gives you a nudge in the right direction.无论如何,我希望这能给你一个正确的方向。 Maybe it would help you to try to write something yourself from scratch.也许它会帮助您尝试从头开始自己编写一些东西。 Even just opening a window.即使只是打开 window。 Then adding key handling.然后添加密钥处理。 Then drawing something... Incrementally add to your knowledge, I think you'll learn much faster this way.然后画一些东西......逐渐增加你的知识,我认为你会这样学得更快。 There's a reason every programming book starts with "Hello World" .每本编程书籍都以“Hello World”开头是有原因的。

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

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