I am currently programming a Pong game in Python. For this, I am using the Python Turtle module. In the Pong game, the main idea is that there are two paddles (one on the left, one on the right) that hit a ball back and forth between them. This is the current state, which is running without any issues:
main.py:
from day22.game_screen import GameScreen
from day22.paddle import Paddle
game_screen = GameScreen()
screen = game_screen.get_screen()
right_paddle = Paddle((350, 0))
left_paddle = Paddle((-350, 0))
screen.listen()
screen.onkey(key="Up", fun=right_paddle.go_up)
screen.onkey(key="Down", fun=right_paddle.go_down)
screen.onkey(key="w", fun=left_paddle.go_up)
screen.onkey(key="s", fun=left_paddle.go_down)
game_is_on = True
while game_is_on:
screen.update()
screen.exitonclick()
paddle.py:
# some code to handle the initialization of the paddles...
game_screen.py:
from turtle import Screen
class GameScreen:
def __init__(self):
self.screen = Screen()
self.screen.bgcolor("black")
self.screen.setup(width=800, height=600)
self.screen.title("Pong")
self.screen.tracer(0)
def get_screen(self):
return self.screen
I wanted to refactor the code so that the GameScreen class inherits from the Screen class of the Turtle module. This would also make the get_screen()
method redundant. So, I did the following refactoring:
game_screen.py:
from turtle import Screen
class GameScreen(Screen):
def __init__(self):
super().__init__()
self.bgcolor("black")
self.setup(width=800, height=600)
self.title("Pong")
self.tracer(0)
main.py:
from day22.game_screen import GameScreen
from day22.paddle import Paddle
game_screen = GameScreen()
right_paddle = Paddle((350, 0))
left_paddle = Paddle((-350, 0))
game_screen.listen()
game_screen.onkey(key="Up", fun=right_paddle.go_up)
game_screen.onkey(key="Down", fun=right_paddle.go_down)
game_screen.onkey(key="w", fun=left_paddle.go_up)
game_screen.onkey(key="s", fun=left_paddle.go_down)
game_is_on = True
while game_is_on:
game_screen.update()
game_screen.exitonclick()
When I run this code now, I get the following error: TypeError: function() argument 'code' must be code, not str
. Is the reason for the error that the Screen class in the Turtle module is marked as a singleton and therefore cannot be inherited from, or am I making another mistake?