Почему функция xcor () черепахи не меняет значения? - PullRequest
0 голосов
/ 19 июня 2020

У меня есть команды правой / левой клавиш, которые перемещают мою черепаху игрока. Проблема в том, что я пытаюсь добавить условие столкновения в игру l oop, но xcor () остается на 0,0, даже если я перемещаю черепаху игрока влево или вправо. Это происходит только в игре l oop. Когда я печатаю xcor () в функциях go_right или go_left, он выводит правильную координату x. Кто-нибудь знает, что происходит?

import turtle as t
import random

class App:
    def __init__(self):
        self.circle1 = Circle(2)

    def game_loop(self):
        self.circle1.drop()


class Circle:

    def __init__(self,size):
        self.size = size
        #self.speed = speed
        self.circle = t.Turtle()
        self.player = Player()
        self.ypos = 300




   def size_color(self):
    self.circle.color('red')
    self.circle.shape('circle')
    self.circle.shapesize(self.size,self.size,1)

#positions circle random x top y
def posit(self):
    number = random.randint(-340,340)
    self.circle.ht()
    self.circle.penup()

    self.size_color()
    self.circle.goto(number,self.ypos)
    self.circle.st()


   #THIS IS WHERE PROBLEM IS
    def drop(self):
        self.posit()
        game = True
        count = 0
        while game:
            self.ypos = self.ypos- 4
            self.circle.sety(self.ypos)
            if self.ypos <= -300:
                self.player.score = self.player.score - 50
                print(self.player.score)
                self.ypos = 300
                self.posit()
            if self.player.score <= 0:
                count = count + 1
                self.player.score = 200
            #xcor() returns 0.0 even when it is clearly not at 0.0
            #Never prints 'hello'
            if self.player.xcor() < 0:
                print('hello')
            if count  == 3:
                print('Game Over')
                game = False



    class Player(t.Turtle):
        def __init__(self,score=200):
            t.Turtle.__init__(self)
            self.score = score
            self.xpos = 0
            self.player = t.Turtle()


       def display_player(self):
            self.player.penup()
            self.player.sety(-200)
            self.player.color('green')
            self.player.shape('square')


       def go_left(self):
            self.xpos = self.xpos - 15
            self.player.setposition(self.xpos,-200)



      def go_right(self):
           self.xpos = self.xpos + 15
           self.player.setposition(self.xpos,-200)




def display_screen():
    window = t.Screen()
    window.bgcolor('black')




display_screen()
player = Player()
player.display_player()

t.listen()
t.onkey(player.go_left,"Left")
t.onkey(player.go_right,"Right")

App().game_loop()

1 Ответ

0 голосов
/ 21 июня 2020

Все, что указывает @jasonharper, действительно (+1). С объектно-ориентированной точки зрения в вашем коде есть серьезные структурные проблемы. Почему препятствия должны отслеживать счет игрока? Этот logi c принадлежит классам Player или App, а не Circle. И похожие проблемы.

Я переработал ваш код ниже, чтобы сделать его в основном воспроизводимым. Вы увидите, что он завершается после дюжины промахов, поскольку код подсчета очков работает. Вам нужно добавить обнаружение столкновений:

from turtle import Screen, Turtle
from random import randint

class App:
    def __init__(self):
        self.circle = Circle()
        self.player = Player()
        self.player.display_player()

        screen.onkey(self.player.go_left, 'Left')
        screen.onkey(self.player.go_right, 'Right')

    def game_loop(self):
        self.circle.posit()

        game = True
        count = 0

        while game:
            touched_bottom = self.circle.drop()

            if touched_bottom:

                self.player.score -= 50

                if self.player.score <= 0:
                    count += 1

                    if count == 3:
                        print('Game Over')
                        game = False
                    else:
                        self.player.score = 200

class Circle:
    def __init__(self, size=2):
        self.size = size
        self.circle = Turtle()
        self.ypos = 300

    def size_color(self):
        self.circle.color('red')
        self.circle.shape('circle')
        self.circle.shapesize(self.size, self.size, 1)

    def posit(self):

        ''' positions circle random x top y '''

        self.circle.hideturtle()
        self.circle.penup()
        self.size_color()
        self.circle.setposition(randint(-340, 340), self.ypos)
        self.circle.showturtle()

    def drop(self):

        ''' Returns True if circle drops below 300 else False '''

        self.ypos -= 4
        self.circle.sety(self.ypos)

        if self.ypos <= -300:
            self.ypos = 300
            self.posit()
            return True

        return False

class Player():
    def __init__(self, score=200):
        self.score = score
        self.xpos = 0
        self.player = Turtle()

    def display_player(self):
        self.player.penup()
        self.player.sety(-200)
        self.player.color('green')
        self.player.shape('square')

    def go_left(self):
        self.xpos -= 15
        self.player.setposition(self.xpos, -200)

    def go_right(self):
        self.xpos += 15
        self.player.setposition(self.xpos, -200)

screen = Screen()
screen.bgcolor('black')

screen.listen()

App().game_loop()
...