社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python turtle module object.hideturtle不工作

Kamil Waniczek • 5 年前 • 1648 次点击  

我在写 Space Invaders game from Christian Thompson 我在第188行遇到了问题,当探测到碰撞时,玩家和敌人躲在那里。我的玩家乌龟在躲,但敌人乌龟不想躲。代码如下:

import turtle
import os
import math
import random
import winsound

#Set up the screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Space Invaders")
wn.bgpic("space_invaders_background.gif")

#Register the shapes
turtle.register_shape("invader.gif")
turtle.register_shape("player.gif")

#Draw border
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("white")
border_pen.penup()
border_pen.setposition(-300,-300)
border_pen.pendown()
border_pen.pensize(3)
for side in range(4):
    border_pen.fd(600)
    border_pen.lt(90)
border_pen.hideturtle()

#Set the score to 0
score = 0

#Draw score
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color("white")
score_pen.penup()
score_pen.setposition(-290, 280)
scorestring = "Score: %s" %score
score_pen.write(scorestring, False, align="left", font=("Arial", 14, "normal"))
score_pen.hideturtle()

#Game Over
game_over = turtle.Turtle()
game_over.speed(0)
game_over.color("red")
game_over.penup()
game_over.setposition(0, 0)
gameOverMsg = "Game Over!"
game_over.hideturtle()


#Create player
player = turtle.Turtle()
player.color("blue")
player.shape("player.gif")
player.penup()
player.speed(0)
player.setposition(0,-230)
player.setheading(90)

playerspeed = 15


#Choose a number of enemies
number_of_enemies = 20
#Create empty list of enemies
enemies = []

#Add enemies to list
for i in range(number_of_enemies):
    # Create the enemy
    enemies.append(turtle.Turtle())

for enemy in enemies:
    enemy.color("red")
    enemy.shape("invader.gif")
    enemy.penup()
    enemy.speed(0)
    x = random.randint(-200, 200)
    y = random.randint(100, 250)
    enemy.setposition(x, y)

enemyspeed = number_of_enemies * 0.5

#Create the player's bullet
bullet = turtle.Turtle()
bullet.color("yellow")
bullet.shape("triangle")
bullet.penup()
bullet.speed(0)
bullet.setheading(90)
bullet.shapesize(0.5, 0.5)
bullet.hideturtle()

bulletspeed = 20

def laser():
    winsound.PlaySound("laser.wav", winsound.SND_ASYNC)
def explosion():
    winsound.PlaySound("explosion.wav", winsound.SND_ASYNC)

#Move the player left and right
def move_left():
    x = player.xcor()
    x -= playerspeed
    if x < -280:
        x = -280
    player.setx(x)

def move_right():
    x = player.xcor()
    x += playerspeed
    if x > 280:
        x = 280
    player.setx(x)

def fire_bullet():
    if not bullet.isvisible():
        laser()
        #Move the bullet to the just above the player
        x = player.xcor()
        y = player.ycor() + 10
        bullet.setposition(x, y)
        bullet.showturtle()

#Checking collision between enemy and bullet
def isCollision(t1, t2) :
    distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
    if distance < 20:
        return True
    else:
        return False

#Create keyboard bindings
turtle.listen()
turtle.onkeypress(move_left, "Left")
turtle.onkeypress(move_right, "Right")
turtle.onkeypress(fire_bullet, "space")

#Main game loop
while True:

    for enemy in enemies:
        #Move the enemy
        x = enemy.xcor()
        x += enemyspeed
        enemy.setx(x)

        #Move the enemy back and down
        if enemy.xcor() > 280:
            #Move all enemies down
            for e in enemies:
                y = e.ycor()
                y -= 40
                e.sety(y)
            #Change enemy direction
            enemyspeed *= -1

        if enemy.xcor() < -280:
            #Move all enemies down
            for e in enemies:
                y = e.ycor()
                y -= 40
                e.sety(y)
            #Change enemy direction
            enemyspeed *= -1

        # Check for a collision between the bullet and the enemy
        if isCollision(bullet, enemy):
            explosion()
            # Reset the bullet
            bullet.hideturtle()
            bullet.setposition(0, -400)
            # Reset the enemy
            x = random.randint(-200, 200)
            y = random.randint(100, 250)
            enemy.setposition(x, y)
            #Update the score
            score += 10
            scorestring = "Score: %s" %score
            score_pen.clear()
            score_pen.write(scorestring, False, align="left", font=("Arial", 14, "normal"))

        if isCollision(player, enemy):
            explosion()
            player.hideturtle()
            enemy.hideturtle()
            game_over.write(gameOverMsg, False, align="center", font=("Arial", 60, "normal"))
            break

    #Move the bullet
    if bullet.isvisible():
        y = bullet.ycor()
        y += bulletspeed
        bullet.sety(y)

    #Check border collision
    if bullet.ycor() > 290:
        bullet.hideturtle()








wn.mainloop()
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43248
 
1648 次点击  
文章 [ 1 ]  |  最新文章 5 年前
cdlane
Reply   •   1 楼
cdlane    6 年前

我无法重现你的问题。我重新编写了下面的代码:我删除了图像和声音,以便任何人都可以运行它并帮助您调试它;我放弃了 isCollision() 编码和替换海龟自己的 distance() 方法;我替换了 while True: Loop,在Turtle这样的事件驱动世界中没有位置,它有一个计时器事件;我已经简化了代码,可以:

from turtle import Screen, Turtle
from random import randint

PLAYER_SPEED = 15
BULLET_SPEED = 20

# Choose a number of enemies
NUMBER_OF_ENEMIES = 20

SMALL_FONT = ('Arial', 14, 'normal')
LARGE_FONT = ('Arial', 60, 'normal')

# Move the player left and right
def move_left():
    x = player.xcor() - PLAYER_SPEED

    if x < -280:
        x = -280

    player.setx(x)

def move_right():
    x = player.xcor() + PLAYER_SPEED

    if x > 280:
        x = 280

    player.setx(x)

def fire_bullet():
    if not bullet.isvisible():
        # Move the bullet to the just above the player
        x, y = player.position()
        bullet.setposition(x, y + 10)
        bullet.showturtle()

# Check collision between enemy and bullet
def isCollision(t1, t2):
    return t1.distance(t2) < 20

# Set up the screen
wn = Screen()
wn.bgcolor('black')
wn.title("Space Invaders")

# Draw border
border_pen = Turtle(visible=False)
border_pen.speed('fastest')
border_pen.color('white')
border_pen.pensize(3)

border_pen.penup()
border_pen.setposition(-300, -300)
border_pen.pendown()

for _ in range(4):
    border_pen.fd(600)
    border_pen.lt(90)

# Set the score to 0
score = 0

# Draw score
score_pen = Turtle(visible=False)
score_pen.speed('fastest')
score_pen.color('white')
score_pen.penup()

score_pen.setposition(-290, 280)
scorestring = "Score: %s" % score
score_pen.write(scorestring, False, align='left', font=SMALL_FONT)

# Game Over
game_over = Turtle(visible=False)
game_over.speed('fastest')
game_over.color('red')
game_over.penup()
gameOverMsg = "Game Over!"

# Create player
player = Turtle('turtle')
player.speed('fastest')
player.color('blue')
player.penup()
player.setposition(0, -230)
player.setheading(90)

# Create empty list of enemies
enemies = []

# Add enemies to list
for _ in range(NUMBER_OF_ENEMIES):
    # Create the enemy
    enemy = Turtle('turtle', visible=False)
    enemy.settiltangle(270)  # for non GIF version of game
    enemy.speed('fastest')
    enemy.color('red')
    enemy.penup()
    enemy.setposition(randint(-200, 200), randint(100, 250))

    enemies.append(enemy)

for enemy in enemies:
    enemy.showturtle()

# Create the player's bullet
bullet = Turtle('triangle', visible=False)
bullet.color('yellow')
bullet.penup()
bullet.speed('fastest')
bullet.setheading(90)
bullet.shapesize(0.5)

# Create keyboard bindings
wn.onkeypress(move_left, 'Left')
wn.onkeypress(move_right, 'Right')
wn.onkeypress(fire_bullet, 'space')
wn.listen()

enemy_speed = NUMBER_OF_ENEMIES * 0.5

# Main game loop
def move():
    global score, enemy_speed

    collision = False

    for enemy in enemies:

        # Move the enemy
        enemy.forward(enemy_speed)

        # Check for a collision between the bullet and the enemy
        if isCollision(bullet, enemy):
            # Reset the bullet
            bullet.hideturtle()
            # Reset the enemy
            enemy.setposition(randint(-200, 200), randint(100, 250))
            # Update the score
            score += 10
            scorestring = "Score: %s" % score
            score_pen.clear()
            score_pen.write(scorestring, False, align='left', font=SMALL_FONT)

        if isCollision(player, enemy):
            player.hideturtle()
            enemy.hideturtle()
            game_over.write(gameOverMsg, False, align='center', font=LARGE_FONT)
            collision = True
            break

    if any(enemy.xcor() < -280 or enemy.xcor() > 280 for enemy in enemies):
        # Move all enemies down
        for enemy in enemies:
            enemy.sety(enemy.ycor() - 40)

        # Change enemy direction
        enemy_speed *= -1

    # Move the bullet
    if bullet.isvisible():
        bullet.forward(BULLET_SPEED)
        # Check border collision
        if bullet.ycor() > 290:
            bullet.hideturtle()

    if not collision:
        wn.ontimer(move, 50)

move()

wn.mainloop()

这个节目对我来说是似曾相识的 with respect to this question 所以看 my answer to it 更多的想法。另外,请看这个答案 another space invaders game in turtle 看看你能从中学到什么来完善你的游戏。