Selaa lähdekoodia

SVI Add chapter 01

SVI 1 kuukausi sitten
vanhempi
commit
b1892aa6a8
6 muutettua tiedostoa jossa 79 lisäystä ja 51 poistoa
  1. 14 19
      doc/part01/ch01.md
  2. 1 1
      nimcity.nimble
  3. 43 0
      src/ball/ball.nim
  4. 12 0
      src/cons.nim
  5. BIN
      src/nimcity
  6. 9 31
      src/nimcity.nim

+ 14 - 19
doc/part01/ch01.md

@@ -1,25 +1,20 @@
-# Part I: Introduction to Nim via graphics
+# Глава 1. Введение
 
-## Chapter 1. Introduction
-
-In this chapter we will show the basics of Nim language (types, for loops, if
-and case statements, procedures, etc.) while using basic graphic primitives to
-create shapes.
-The premise is that the putPixel proc exists and we can use it, not worrying
-about its implementation details. All we need to know is: that proc takes the x
-and y coordinate of a point and its Color (default: white), and places a pixel of
-that color at those coordinates for us. This is how to use it:
+В этой главе мы рассмотрим основы языка **Nim** (типы, циклы `for`, операторы `if` и `case`, процедуры и т. д.), используя базовые графические примитивы для создания фигур. Предполагается, что процедура `putPixel` существует и мы можем ее использовать, не беспокоясь о деталях ее реализации. Все, что нам нужно знать: эта процедура принимает координаты `x` и `y` точки, а также ее цвет (по умолчанию — белый) и размещает в этих координатах пиксель указанного цвета. Вот как ее использовать:
 
 ```nim
- import pixels  # 1
- putPixel(5, 9)          # 2
- putPixel(11, 18, Red)  # 3
+import pixels         # 1
+
+putPixel(5, 9)        # 2
+putPixel(11, 18, Red) # 3
 ```
 
-- 1 We import pixels so we can use the putPixel proc.
-- 2 Puts a white (that is the default color) pixel at the (5, 9) coordinate.
-- 3 Puts a red pixel at the (11, 18) coordinate.
+- 1 Мы импортируем пиксели, чтобы использовать процедуру `putPixel`.
+- 2 Помещает белый (цвет по умолчанию) пиксель в координаты (5, 9).
+- 3 Помещает красный пиксель в координаты (11, 18).
 
-Your Nim installation ships with a package manager called Nimble. Nimble
-can install additional packages. You can install the pixels library via:
- nimble install pixels
+В вашей установке **Nim** есть менеджер пакетов под названием **Nimble**. **Nimble** может устанавливать дополнительные пакеты. Вы можете установить библиотеку **pixels** с помощью:
+
+```bash
+nimble install pixels
+```

+ 1 - 1
nimcity.nimble

@@ -19,4 +19,4 @@ task prod, "Сборка для прода":
 
 task dev, "Сборка для отладки":
   # Exec запускает внешнюю команду (в данном случае компилятор Nim)
-  exec "nim c -d:debug ./src/nimcity.nim"
+  exec "nim c -r -d:debug ./src/nimcity.nim"

+ 43 - 0
src/ball/ball.nim

@@ -0,0 +1,43 @@
+import random
+
+import ../cons
+
+type
+  Ball* = ref object
+    x, y: float32
+    vx, vy: float32
+
+proc NewBall*(): Ball =
+  Ball(
+    x: WindowWidth / 2 - BallRadius,
+    y: WindowHeight / 2 - BallRadius,
+    vx: (rand(2.0) - 1) * 100,
+    vy: (rand(2.0) - 1) * 300
+  )
+
+proc `x`*(sf: Ball):float32{.inline.}=
+    return sf.x
+
+proc `dtx`*(sf: Ball, dt:float32){.inline.}=
+    sf.x += sf.vx * dt
+
+proc `y`*(sf: Ball):float32{.inline.}=
+    return sf.y
+
+proc `dty`*(sf: Ball, dt:float32){.inline.}=
+    sf.y += sf.vy * dt
+
+proc reset_y*(sf: Ball){.inline.}=
+    sf.y=0
+
+proc `vy`*(sf: Ball):var float32{.inline.}=
+    return sf.vy
+
+proc `y=`*(sf: Ball, val: float32){.inline.}=
+    sf.y=val
+
+proc `vx`*(sf: Ball):var float32{.inline.}=
+    return sf.vx
+
+proc `x=`*(sf: Ball, val: float32){.inline.}=
+    sf.x=val

+ 12 - 0
src/cons.nim

@@ -2,5 +2,17 @@ const
     orgName*:string = "SVI"
     appName*:string = "nimсity"
 
+    WindowWidth*  = 640
+    WindowHeight* = 480
 
+    PaddleWidth*  = 16
+    PaddleHeight* = 64
+    PaddleSpeed*  = 400.0
+
+    BallRadius* = 8
+
+    MaxBallComponentSpeed* = 1000'f32
+
+    TextWidth*  = 128
+    TextHeight* = 64
 

BIN
src/nimcity


+ 9 - 31
src/nimcity.nim

@@ -3,29 +3,13 @@ import random
 import sdl2
 import sdl2/ttf
 
-const
-  WindowWidth = 640
-  WindowHeight = 480
-
-  PaddleWidth = 16
-  PaddleHeight = 64
-  PaddleSpeed = 400.0
-
-  BallRadius = 8
-
-  MaxBallComponentSpeed = 1000'f32
-
-  TextWidth = 128
-  TextHeight = 64
+import ./cons
+import ./ball/ball
 
 type
   Paddle = ref object
     x, y: float32
 
-  Ball = ref object
-    x, y: float32
-    vx, vy: float32
-
   Input {.pure.} = enum
     Up,
     Down,
@@ -46,13 +30,7 @@ proc newPaddle(x: float32): Paddle =
     y: (WindowHeight + PaddleHeight) / 2,
   )
 
-proc newBall(): Ball =
-  Ball(
-    x: WindowWidth / 2 - BallRadius,
-    y: WindowHeight / 2 - BallRadius,
-    vx: (rand(2.0) - 1) * 100,
-    vy: (rand(2.0) - 1) * 300
-  )
+
 
 func collision(ball: Ball, paddle: Paddle): bool =
   return not (
@@ -99,12 +77,12 @@ proc speedup(v: var float32) =
   v = min(v,  MaxBallComponentSpeed)
 
 proc updateBall(g: Game, dt: float32) =
-  g.ball.x += g.ball.vx * dt
-  g.ball.y += g.ball.vy * dt
+  g.ball.dtx(dt)
+  g.ball.dty(dt)
 
   # bounce on upper and lower borders, add speedup on bounce
   if g.ball.y < 0:
-    g.ball.y = 0
+    g.ball.reset_y()
     bounce(g.ball.vy)
     speedup(g.ball.vx)
   elif g.ball.y + 2 * BallRadius > WindowHeight:
@@ -125,12 +103,12 @@ proc updateBall(g: Game, dt: float32) =
   # opponent scored
   if g.ball.x + 2 * BallRadius < 0:
     inc g.scores.opponent
-    g.ball = newBall()
+    g.ball = NewBall()
 
   # player scored
   elif g.ball.x > WindowWidth:
     inc g.scores.player
-    g.ball = newBall()
+    g.ball = NewBall()
 
 
 proc draw(renderer: RendererPtr, paddle: Paddle) =
@@ -174,7 +152,7 @@ proc newGame(): Game =
     running: true,
     player: newPaddle(PaddleWidth),
     opponent: newPaddle(WindowWidth - 2 * PaddleWidth),
-    ball: newBall(),
+    ball: NewBall(),
     scores: (0'u, 0'u)
   )