1
+ """
2
+ I chose these import statements just to make my close look cleaner
3
+ For this to work you would just need to import cocos and then add the subdirectory after
4
+ Ex: self.label = Label(...) would be self.sprite = cocos.text.Label(...)
5
+ """
6
+ import cocos
7
+ from cocos .text import Label
8
+ from cocos import scene
9
+ from cocos .layer import Layer
10
+ from cocos .director import director
11
+
12
+
13
+ # This code is an explained version of the Hello World example from the Cocos2D Python documentation
14
+ # We will be making a simple game that displays the text "Hello World!"
15
+
16
+ # First I create a class that extends the Layer class from the Cocos library.
17
+ # If you don't know what this is you should probably take an object oriented programming course first
18
+ class HelloWorld (Layer ):
19
+ # Each python class needs an __init__ function that is called when an object is instantiated
20
+ def __init__ (self ):
21
+ # First you need to initialize the parent class, Layer, which is why I called the super function in this case
22
+ super (HelloWorld , self ).__init__ ()
23
+ # First I make a Cocos Label object to display the text.
24
+ hello_world_label = Label (
25
+ "Hello World!" , # The first thing the Label class requires is a piece of text to display
26
+ font_name = "Times New Roman" , # The next thing we need to input a font. Feel free to replace it with any font you like.
27
+ font_size = 32 , # The third input I give is a font size for the text
28
+ anchor_x = 'center' , # This input parameter tells cocos to anchor the text to the middle of the X axis
29
+ anchor_y = 'center' # Similar to the input above, this parameter tells cocos to anchor the text to the middle of the Y axis
30
+ )
31
+
32
+ # Now I need to give the text its position.
33
+ hello_world_label .position = 320 , 240
34
+
35
+ # Lastly I need to add the label to the layer
36
+ # self refers to the object, which in this case is the layer
37
+ self .add (hello_world_label )
38
+
39
+
40
+ # From here the code is pretty typical for a Cocos2D application
41
+ # First I need to initialize the cocos director
42
+ # The director is the part of cocos that "directs" the scenes. Cocos is pretty partial to this type of film language
43
+ director .init ()
44
+ # Lastly I run the scene. This line of code is pretty long compared to the others, so I'll explain what each part does
45
+ # To begin I call the director's run function, which allows it to run the scene by placing layers within
46
+ director .run (
47
+ # Next I create a Scene object that allows me to string the layers together. In this case I only have 1 layer
48
+ scene .Scene (
49
+ # And lastly I create the layer that we made above inside of the new scene
50
+ HelloWorld ()
51
+ )
52
+ )
53
+
54
+ # That's it! Run it and see what happens
0 commit comments