ผลต่างระหว่างรุ่นของ "Prg2/arcade1"
Jittat (คุย | มีส่วนร่วม) |
Jittat (คุย | มีส่วนร่วม) |
||
(ไม่แสดง 9 รุ่นระหว่างกลางโดยผู้ใช้คนเดียวกัน) | |||
แถว 54: | แถว 54: | ||
==== 1. Installing pip on Windows ==== | ==== 1. Installing pip on Windows ==== | ||
− | pip | + | <tt>pip</tt> comes with python. Don't forget to check an option to include pip. If it's not available on the command line, try to install Python 3 again. |
− | * | + | * Read instructions here: [https://pythonhosted.org/arcade/installation_windows.html arcade installation บน windows] |
==== 2. Installing pip3 on Linux ==== | ==== 2. Installing pip3 on Linux ==== | ||
− | + | Install pip3 with other programs with | |
sudo apt install -y python3-dev python3-pip libjpeg-dev zlib1g-dev | sudo apt install -y python3-dev python3-pip libjpeg-dev zlib1g-dev | ||
− | ==== 3. | + | ==== 3. Installing pip3 on Mac ==== |
− | + | <tt>pip3</tt> usually comes with Python 3. Try to call it from the terminal. | |
− | + | On Mac, you have to install <tt>libjpg</tt>. If you have <tt>homebrew</tt>, call | |
brew install libjpeg | brew install libjpeg | ||
− | + | If it doesn't work, download and install from [http://ethan.tira-thompson.com/Mac_OS_X_Ports.html]. (choose libjpg) | |
=== Use pip to install arcade === | === Use pip to install arcade === | ||
− | For Ubuntu, | + | For Ubuntu, install arcade using pip (or pip3) with |
sudo pip3 install arcade | sudo pip3 install arcade | ||
แถว 88: | แถว 88: | ||
pip install arcade | pip install arcade | ||
− | ''' | + | '''Remarks:''' If you install arcade with <tt>pip</tt>, but <tt>pip</tt> puts it in Python 3.5's packages, use the following command to install: |
python3.6 -m pip install arcade | python3.6 -m pip install arcade | ||
=== virtualenv === | === virtualenv === | ||
− | + | We install <tt>arcade</tt> into the system's library. If you work intensively with Python, having many packages in the system may causes version clashes, you might want to install library locally using ''virtualenv''. Try to google it if you want to try. | |
: ''Sorry NOT READY: to do - how to install with virtualenv'' | : ''Sorry NOT READY: to do - how to install with virtualenv'' | ||
แถว 241: | แถว 241: | ||
== Many circles == | == Many circles == | ||
− | + | After this point, we will refer to circles as balls interchangeably. | |
− | + | We will modify our code so that we have many moving circles. Save the new code for this section in file <tt>cir2.py</tt>. | |
+ | |||
+ | We will random the circle locations and speeds with <tt>randint</tt> function; therefore, you should add the following import statements at the beginning of the code. | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 250: | แถว 252: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | We use lists to keep circles' co-ordinates and speeds in lists <tt>xs, ys, vxs, vys</tt> and the number of circles. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 267: | แถว 269: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | The following function <tt>draw_and_move_circle</tt> handles the i-th ball in the list. Function <tt>on_draw</tt> will call this function. Note that the code below does not include the code for bouncing with screen edges. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 276: | แถว 278: | ||
arcade.draw_circle_outline(xs[i], ys[i], 20, arcade.color.BLACK) | arcade.draw_circle_outline(xs[i], ys[i], 20, arcade.color.BLACK) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | ||
− | <tt>on_draw</tt> | + | Function <tt>on_draw</tt> iteratively calls <tt>draw_and_move_circle</tt>. |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 287: | แถว 289: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | We are ready to add our main function. Don't forget to call <tt>initialize</tt> in it. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 301: | แถว 303: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | Finally, add the code to call the main function. | |
− | + | <syntaxhighlight lang="python"> | |
+ | if __name__ == '__main__': | ||
+ | main() | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | Try to run the code to see if it works. | ||
+ | |||
+ | '''Quick question:''' What can you do to improve the current code to make it more readable and maintainable? | ||
+ | |||
+ | === Split the function === | ||
+ | |||
+ | Function <tt>draw_and_move_circle</tt> is a good example of a function that tries to do too many things. We will split it into two functions and calls them in <tt>on_draw</tt>. | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 320: | แถว 333: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | === | + | === Exercise 2: Bounce === |
− | + | The program with many balls does not deal with screen edges. Modify function <tt>move_circle</tt> so that it checks the situation and updates the balls speeds so that the balls bounce at the screen edges. | |
== The Circle class == | == The Circle class == | ||
− | + | Observe that for each ball, we maintain four variables, i.e., <tt>x, y, vx,</tt> and <tt>vy</tt>. We shall '''extract''' these variables into a class '''<tt>Circle</tt>''' | |
− | + | Move all code into file <tt>cir3.py</tt>. | |
− | + | Clsss <tt>Circle</tt> can be written as follows. Note that class methods have additional <tt>self</tt> argument that represents the current object the methods are dealing with. Method <tt>__init__</tt> is a special one that initializes the object. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 343: | แถว 356: | ||
self.y += self.vy | self.y += self.vy | ||
− | # | + | # TODO: add the bouncing code here. |
def draw(self): | def draw(self): | ||
แถว 350: | แถว 363: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | With class Circle, we update the code that creates the balls. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 365: | แถว 378: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | Also, we need to modify <tt>on_draw</tt>. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 373: | แถว 386: | ||
for c in circles: | for c in circles: | ||
c.move() | c.move() | ||
− | c.draw() | + | c.draw() |
</syntaxhighlight> | </syntaxhighlight> | ||
− | === | + | === Exercise 3: Circles of many sizes === |
− | + | ||
+ | We add variable <tt>r</tt> into class Circle with a default of 20. | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 390: | แถว 404: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | Modify the rest of the code so that the programs generates balls with different sizes and shows these balls on the screen. | |
== A simple ball game == | == A simple ball game == | ||
− | + | We will write a simple game. Copy the code from the previous section into file <tt>cir4.py</tt> and work on this new file. | |
− | + | We define class '''Player'''. We show on screen as a blue ball with radius 10. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 408: | แถว 422: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | Add the code for creating an object of class Player near the code where we declare <tt>circles</tt>. (Operator // is an integer division.) | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 416: | แถว 430: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | Show the player in <tt>on_draw</tt>. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 429: | แถว 443: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | === | + | === Move the player === |
− | + | We shall control the player through the keyboard. This step is technically tedious because we have to read the keyboard statuses. In later tutorials, we will use a simpler method. | |
− | ==== | + | ==== Preparing to read keys ==== |
− | + | We will use library <tt>pyglet</tt> to read the keyboard statuses. So you have to import it at the beginning of the code. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 458: | แถว 472: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | ==== | + | ==== The player's control ==== |
− | + | Add method <tt>control</tt> in class <tt>Player</tt>. The code currently detects only the LEFT key. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
class Player: | class Player: | ||
− | # ... | + | # ... old code hidden |
def control(self, keys): | def control(self, keys): | ||
แถว 471: | แถว 485: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | Function <tt>on_draw</tt> then calls <tt>player.control</tt> to inform the player of the key pressed. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 485: | แถว 499: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | ==== | + | ==== Exercise 4: all the arrows ==== |
− | + | Modify <tt>Player.control</tt> so that it detects key pressed for all other directions (e.g., up, down, right). | |
− | === | + | === Exercise 5: Collision detection === |
− | + | Write method <tt>is_hit</tt> that detects collision between the player and a circle. | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
class Player: | class Player: | ||
− | # ... | + | # ... other code hidden |
def is_hit(self, circle): | def is_hit(self, circle): | ||
− | # ... | + | # ... checks of self hits with circle |
− | # | + | # The method should consider self.x, self.y and circle.x and circle.y with radius circle.r |
− | # | + | # Don't forget that the player has radius of 10 |
# | # | ||
− | # method | + | # The method should return True or False |
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | You can use <tt>is_hit</tt> in <tt>on_draw</tt>. If the player is hit, the code stops (with <tt>quit()</tt>). | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
แถว 520: | แถว 534: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | If your game is too hard (you get instantly dead), you should reduce the number of balls or try to random balls not too close to the center. | |
− | === | + | === Exercise 6: smoother end === |
− | + | Instead of just call <tt>quit()</tt> to quit instantly, you should change the code so that it ends more smoothly, e.g., all balls stop or the player get hidden. | |
− | == | + | == Exercise 100: Hit and bounce == |
− | + | If you are at this point, try to modify the game so that the balls bounce when they hit each other. |
รุ่นแก้ไขปัจจุบันเมื่อ 02:48, 18 มกราคม 2562
- This page is a part of Programming 2 (translated from Oop lab/oop in python)
We will start learning how to use the Arcade library and also get a quick review on OOP concepts.
เนื้อหา
Installing Arcade
We will use the arcade game library which requires at least Python 3.6.
Python 3.6
Let's make sure that you have a proper version of Python. Let's call python from the command line (or terminal)
python --version
If its version is at least 3.6, you are good to go and you can skill to the next step (pip installation). Otherwise, you have to get Python 3.6.
Installing Python 3.6 on Windows
You can follow this instruction. Don't forget to click "Add Python 3.6 to PATH".
Installing Python 3.6 on Ubuntu (version 16.10 onward)
Call
sudo apt-get update sudo apt-get install python3.6
You can call python3.6 to start python 3.6.
Installing Python 3.6 on older Ubuntu
sudo add-apt-repository ppa:jonathonf/python-3.6 sudo apt-get update sudo apt-get install python3.6
Installing Python 3.6 on Mac
Follow this instruction.
Installing pip/pip3
pip is a library package manager for Python. In a system with both Python 3 and Python 2, we would call pip3 to install libraries into Python 3 packages.
Try to call
pip
or
pip3
If it runs, you can skip the pip installation part.
1. Installing pip on Windows
pip comes with python. Don't forget to check an option to include pip. If it's not available on the command line, try to install Python 3 again.
- Read instructions here: arcade installation บน windows
2. Installing pip3 on Linux
Install pip3 with other programs with
sudo apt install -y python3-dev python3-pip libjpeg-dev zlib1g-dev
3. Installing pip3 on Mac
pip3 usually comes with Python 3. Try to call it from the terminal.
On Mac, you have to install libjpg. If you have homebrew, call
brew install libjpeg
If it doesn't work, download and install from [1]. (choose libjpg)
Use pip to install arcade
For Ubuntu, install arcade using pip (or pip3) with
sudo pip3 install arcade
For Mac, use
pip3 install PyObjC arcade
For Windows, use
pip install arcade
Remarks: If you install arcade with pip, but pip puts it in Python 3.5's packages, use the following command to install:
python3.6 -m pip install arcade
virtualenv
We install arcade into the system's library. If you work intensively with Python, having many packages in the system may causes version clashes, you might want to install library locally using virtualenv. Try to google it if you want to try.
- Sorry NOT READY: to do - how to install with virtualenv
Testing your installation
Copy the following code into cirtest.py and try to run it.
import arcade
from random import randint
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
circle_size = 1
size_direction = 1
circle_xs = []
circle_ys = []
num_circles = 100
def random_locations():
for i in range(num_circles):
circle_xs.append(randint(10,SCREEN_WIDTH-10))
circle_ys.append(randint(10,SCREEN_HEIGHT-10))
def on_draw(delta_time):
global circle_size, size_direction
circle_size += size_direction
if circle_size > 50:
size_direction = -1
elif circle_size == 1:
size_direction = 1
arcade.start_render()
for x,y in zip(circle_xs, circle_ys):
arcade.draw_circle_outline(x, y, circle_size, arcade.color.BLACK)
def main():
random_locations()
arcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT,
"Circles")
arcade.set_background_color(arcade.color.WHITE)
arcade.schedule(on_draw, 1 / 80)
arcade.run()
if __name__ == '__main__':
main()
Quick notes:
- randint -- Random integers between to specified numbers. You need to import random.
- global -- In Python, a function can only read from global variables, by default. If you want to change the variables, you have to declare it explicitly. In function on_draw we would like to change the circle size, so we have to declare that. It is not a good practice to use global variables.
- zip -- zip combines to lists, e.g., zip([1,2,3],['a','b','c']) would return [(1, 'a'), (2, 'b'), (3, 'c')]. We usually use zip when we iterate through two lists in a for loop.
- Functions from arcade
- arcade.start_render -- Call this before you want to draw a screen. It will clear the screen. (Some experiment below.)
- arcade.draw_circle_outline -- Draw a circle
- arcade.open_window
- arcade.set_background_color
- arcade.schedule
- arcade.run
A moving circle
Drawing a circle
We will start from a very simple program and will move on to more functioning programs. The code below draws a circle at the center of the screen. Take the code and save it as cir1.py.
import arcade
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
def on_draw(delta_time):
arcade.start_render()
x = 300
y = 300
arcade.draw_circle_outline(x, y, 20, arcade.color.BLACK)
def main():
arcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT,
"Circles")
arcade.set_background_color(arcade.color.WHITE)
arcade.schedule(on_draw, 1 / 80)
arcade.run()
if __name__ == '__main__':
main()
Try to run it. What do you see?
Experiment: Try to remove the line arcade.start_render(). What do you observe?
Move
We will move the circle by having velocities vx (for the x-axis velocity) and vy (for the y-axis velocity).
Because we would like to keep track of the circle location, we will need global variables x and y to keep the circle co-ordinate. We will use global variables for that and in function on_draw we will use keyword global to explicitly tell Python that we will modify these variables. We will also declare that we will modify vx and vy (because later on we will let the circle bounce at the edges of the screen.)
The updated code for on_draw is shown below. The lines that define x,y,vx,vy assign values to global variables.
vx = 2
vy = 1
x = 300
y = 300
def on_draw(delta_time):
arcade.start_render()
global x, y, vx, vy
x += vx
y += vy
arcade.draw_circle_outline(x, y, 20, arcade.color.BLACK)
Exercise 1: Bounce
Currently, when the circle hits the edge of the screen, it will keep moving and will be gone forever. Add a code that checks this situation and change the direction of the circle so that it looks like the circle bounces with the screen edge.
def on_draw(delta_time):
arcade.start_render()
global x, y, vx, vy
x += vx
y += vy
# TODO: add the code for checking if the circle location is a the edge of the screen
# hint: it would be easier to consider each axis separately
arcade.draw_circle_outline(x, y, 20, arcade.color.BLACK)
Many circles
After this point, we will refer to circles as balls interchangeably.
We will modify our code so that we have many moving circles. Save the new code for this section in file cir2.py.
We will random the circle locations and speeds with randint function; therefore, you should add the following import statements at the beginning of the code.
import arcade
from random import randint
We use lists to keep circles' co-ordinates and speeds in lists xs, ys, vxs, vys and the number of circles.
vxs = []
vys = []
xs = []
ys = []
n = 10
def initialize():
for i in range(n):
xs.append(randint(100, SCREEN_WIDTH-100))
ys.append(randint(100, SCREEN_HEIGHT-100))
vxs.append(randint(-5,5))
vys.append(randint(-5,5))
The following function draw_and_move_circle handles the i-th ball in the list. Function on_draw will call this function. Note that the code below does not include the code for bouncing with screen edges.
def draw_and_move_circle(i):
xs[i] += vxs[i]
ys[i] += vys[i]
arcade.draw_circle_outline(xs[i], ys[i], 20, arcade.color.BLACK)
Function on_draw iteratively calls draw_and_move_circle.
def on_draw(delta_time):
arcade.start_render()
for i in range(n):
draw_and_move_circle(i)
We are ready to add our main function. Don't forget to call initialize in it.
def main():
initialize()
arcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT,
"Circles")
arcade.set_background_color(arcade.color.WHITE)
arcade.schedule(on_draw, 1 / 80)
arcade.run()
Finally, add the code to call the main function.
if __name__ == '__main__':
main()
Try to run the code to see if it works.
Quick question: What can you do to improve the current code to make it more readable and maintainable?
Split the function
Function draw_and_move_circle is a good example of a function that tries to do too many things. We will split it into two functions and calls them in on_draw.
def move_circle(i):
# .... อย่าลืมย้ายโค้ดมา
def draw_circle(i):
# .... อย่าลืมย้ายโค้ดมา
def on_draw(delta_time):
arcade.start_render()
for i in range(n):
move_circle(i)
draw_circle(i)
Exercise 2: Bounce
The program with many balls does not deal with screen edges. Modify function move_circle so that it checks the situation and updates the balls speeds so that the balls bounce at the screen edges.
The Circle class
Observe that for each ball, we maintain four variables, i.e., x, y, vx, and vy. We shall extract these variables into a class Circle
Move all code into file cir3.py.
Clsss Circle can be written as follows. Note that class methods have additional self argument that represents the current object the methods are dealing with. Method __init__ is a special one that initializes the object.
class Circle:
def __init__(self, x, y, vx, vy):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
def move(self):
self.x += self.vx
self.y += self.vy
# TODO: add the bouncing code here.
def draw(self):
arcade.draw_circle_outline(self.x, self.y,
20, arcade.color.BLACK)
With class Circle, we update the code that creates the balls.
circles = []
n = 10
def initialize():
for i in range(n):
circle = Circle(randint(100, SCREEN_WIDTH-100),
randint(100, SCREEN_HEIGHT-100),
randint(-5,5),
randint(-5,5))
circles.append(circle)
Also, we need to modify on_draw.
def on_draw(delta_time):
arcade.start_render()
for c in circles:
c.move()
c.draw()
Exercise 3: Circles of many sizes
We add variable r into class Circle with a default of 20.
class Circle:
def __init__(self, x, y, vx, vy, r=20):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
self.r = r
# ...
Modify the rest of the code so that the programs generates balls with different sizes and shows these balls on the screen.
A simple ball game
We will write a simple game. Copy the code from the previous section into file cir4.py and work on this new file.
We define class Player. We show on screen as a blue ball with radius 10.
class Player:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
arcade.draw_circle_filled(self.x, self.y,
10, arcade.color.BLUE)
Add the code for creating an object of class Player near the code where we declare circles. (Operator // is an integer division.)
circles = []
player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
n = 10
Show the player in on_draw.
def on_draw(delta_time):
arcade.start_render()
for c in circles:
c.move()
c.draw()
player.draw()
Move the player
We shall control the player through the keyboard. This step is technically tedious because we have to read the keyboard statuses. In later tutorials, we will use a simpler method.
Preparing to read keys
We will use library pyglet to read the keyboard statuses. So you have to import it at the beginning of the code.
from pyglet.window import key
เราจะประกาศตัวแปร keys เพื่อใช้อ่านสถานะการกดปุ่ม ให้ใส่ไว้ก่อน on_draw โดยอาจจะประกาศไว้แถว ๆ ที่เราประกาศตัวแปร circles, players, และ n ก็ได้
# ... โค้ดเก่า
circles = []
player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
n = 10
# ประกาศ keys
keys = key.KeyStateHandler()
ในฟังก์ชัน main ไปบอกกับหน้าต่างให้อัพเดทสถานะการกดปุ่มผ่านทาง keys โดยเพิ่มบรรทัด push_handlers ให้ใส่ไว้ก่อน arcade.schedule
arcade.get_window().push_handlers(keys)
# .. โค้ดเก่า ...
arcade.schedule(on_draw, 1 / 80)
The player's control
Add method control in class Player. The code currently detects only the LEFT key.
class Player:
# ... old code hidden
def control(self, keys):
if keys[key.LEFT]:
self.x -= 5
Function on_draw then calls player.control to inform the player of the key pressed.
def on_draw(delta_time):
arcade.start_render()
for c in circles:
c.move()
c.draw()
player.control(keys)
player.draw()
Exercise 4: all the arrows
Modify Player.control so that it detects key pressed for all other directions (e.g., up, down, right).
Exercise 5: Collision detection
Write method is_hit that detects collision between the player and a circle.
class Player:
# ... other code hidden
def is_hit(self, circle):
# ... checks of self hits with circle
# The method should consider self.x, self.y and circle.x and circle.y with radius circle.r
# Don't forget that the player has radius of 10
#
# The method should return True or False
You can use is_hit in on_draw. If the player is hit, the code stops (with quit()).
def on_draw(delta_time):
arcade.start_render()
for c in circles:
c.move()
c.draw()
if player.is_hit(c):
quit()
player.draw()
player.control(keys)
If your game is too hard (you get instantly dead), you should reduce the number of balls or try to random balls not too close to the center.
Exercise 6: smoother end
Instead of just call quit() to quit instantly, you should change the code so that it ends more smoothly, e.g., all balls stop or the player get hidden.
Exercise 100: Hit and bounce
If you are at this point, try to modify the game so that the balls bounce when they hit each other.