Проблема с координатами в простой игре на совпадение квадратов в PythonPython

Программы на Python
Ответить
Anonymous
 Проблема с координатами в простой игре на совпадение квадратов в Python

Сообщение Anonymous »

Я создаю простую игру на соответствие квадратов на Python, которая сначала выбирает квадраты случайного цвета и помещает их на экран, чтобы они заполнили экран. Затем игрок рандомизирует позиции квадратов и пытается сопоставить квадрат со стартовыми позициями. Если он соответствует ему, следующий квадрат начинает двигаться, и он должен соответствовать ему.
Мои квадраты слишком велики из-за начального размера квадрата в пикселях (21x21), который я не могу изменить, но это побочная проблема.
Я написал код, который проверяет, находится ли квадрат в правильном положении, но он не работает с нижним левым квадратом, и я не знаю почему... Каждый раз, когда я запускаю код, я могу сопоставить каждый квадрат, и все работает кроме одного квадрата.
Я занимаюсь программированием один месяц, поэтому любая критика по поводу эффективности моего кода будет полезна!
У меня есть 3 файла:
main.py:
from turtle import Screen
from squares_manager import Square
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.tracer(0)
game_is_on = True

scoreboard = Scoreboard()
scoreboard.starting_writing()

square = Square()

def combine_starting_functions():
square.create_start_square()
scoreboard.when_game_starts()
square.squares_starting_pos()

screen.listen()
screen.onkey(combine_starting_functions, "space")
screen.onkey(square.randomize_squares, "Return")
screen.onkeypress(square.move_down, "Down")
screen.onkeypress(square.move_right, "Right")
screen.onkeypress(square.move_left, "Left")
screen.onkeypress(square.move_up, "Up")

while game_is_on:
screen.update()

screen.exitonclick()

square_manager.py:
from turtle import Turtle
import random

COLORS = ["red", "blue", "pink", "yellow", "green", 'purple', "orange", "white", "brown", "cyan", "firebrick",
"dark magenta", "peach puff", "salmon", "dark violet", "spring green"]

STARTING_SIZE = 600

class Square(Turtle):
def __init__(self):
super().__init__()
self.number_of_squares = 2
self.level = self.number_of_squares ** 2
self.squares = []
self.positions = []
self.list_squares_to_move = []
self.distance_between = STARTING_SIZE / self.number_of_squares
self.half_of_square = self.distance_between / 2
for square in range(self.level):
self.list_squares_to_move.append(square)
self.which_square = random.choice(self.list_squares_to_move)

def create_start_square(self):
for square in range(self.level):
new_square = Turtle()
new_square.hideturtle()
new_square.shape("square")
# new_square.shape("/Users/Łukasz/Desktop/20x20square.gif")
ran_color = random.choice(COLORS)
new_square.color(ran_color)
COLORS.remove(ran_color)
new_square.penup()
new_square.turtlesize((STARTING_SIZE / 20) / self.number_of_squares)
self.squares.append(new_square)

def squares_starting_pos(self):
increment_next_square_x = 0
increment_next_square_y = 0
for square in self.squares:
square.showturtle()
square.goto((-self.half_of_square) + increment_next_square_x, self.half_of_square + increment_next_square_y)
increment_next_square_x += self.distance_between
if square.xcor() > 300:
square.setx(-300 + self.half_of_square)
square.right(90)
square.forward(self.distance_between)
increment_next_square_y -= self.distance_between
increment_next_square_x = self.distance_between
self.positions.append(square.position())
print(self.positions)

def randomize_squares(self):
for square in self.squares:
square.goto(random.randint(-300 + self.half_of_square, 300 - self.half_of_square), random.randint
(-300 + self.half_of_square, 300 - self.half_of_square))
square.setheading(90)

# def level_up(self):
# self.number_of_squares += 1

def move_up(self):
self.squares[self.which_square].forward(1)
self.check_square_position()

def move_down(self):
self.squares[self.which_square].backward(1)
self.check_square_position()

def move_right(self):
self.squares[self.which_square].right(90)
self.squares[self.which_square].forward(1)
self.squares[self.which_square].left(90)
self.check_square_position()

def move_left(self):
self.squares[self.which_square].left(90)
self.squares[self.which_square].forward(1)
self.squares[self.which_square].right(90)
self.check_square_position()

def check_square_position(self):
print(self.squares[self.which_square].position())
print(self.positions[self.which_square])
if self.squares[self.which_square].position() == self.positions[self.which_square]:
self.list_squares_to_move.remove(self.which_square)
self.next_square_to_move()
print(self.list_squares_to_move)

def next_square_to_move(self):
self.which_square = random.choice(self.list_squares_to_move)

scoreboard_py:
from turtle import Turtle

class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.hideturtle()
self.penup()

def starting_writing(self):
self.pencolor("white")
self.home()
self.pendown()
self.write("TO SEE STARTING POSITION PRESS SPACE BAR \n AFTER THAT PRESS ENTER TO START A GAME \n "
" TO MOVE PRESS ARROWS", False, "center"
, ("arial", 15, "bold"))
self.penup()

def when_game_starts(self):
self.clear()
self.hideturtle()


Подробнее здесь: https://stackoverflow.com/questions/757 ... -in-python
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»