Python: Game Rắn săn mồi bằng Turtle trong Python

Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực

Trò chơi rắn là một trò chơi mê cung được phát triển bởi Gremlin Industries và được xuất bản bởi Sega vào tháng 10 năm 1976. Đây được coi là một trò chơi khéo léo và đã phổ biến trong mọi người qua nhiều thế hệ. Con rắn trong trò chơi Snake được điều khiển bằng cách sử dụng bốn nút hướng liên quan đến hướng nó đi tới. Mục tiêu của người chơi trong trò chơi là đạt được điểm tối đa bằng cách thu thập thức ăn hoặc trái cây. Người chơi sẽ thua một khi con rắn va vào tường hoặc trúng chính nó.

Đối với người mới bắt đầu sử dụng python, những người quan tâm đến việc tạo ra thứ gì đó dễ dàng hơn trong miền của bạn chắc chắn có thể thử điều này và mô-đun Turtle được tạo chính xác cho mục đích này để người mới bắt đầu dùng thử và cũng có thể gửi như một phần của dự án. Chương trình này sẽ được thực hiện bằng Python 3.

Vì vậy, chúng ta sẽ tạo một trò chơi dựa trên Python bằng cách sử dụng các mô-đun sau:

  • Turtle: Đây là một thư viện python được cài đặt sẵn cho phép người dùng tạo hình dạng và hình ảnh bằng cách cung cấp cho họ một canvas ảo.
  • Time: Chức năng này được sử dụng để đếm số giây đã trôi qua.
  • Random: Hàm này được sử dụng để tạo các số ngẫu nhiên trong Python bằng cách sử dụng mô-đun random.

Dưới đây là các bước tạo game Rắn săn mồi.

Bước 1 : Chúng ta sẽ đưa vào các mô-đun và đưa ra các giá trị mặc định cho trò chơi.

# Đưa vào các module cần thiết
import turtle
import time
import random

delay = 0.1
score = 0
high_score = 0

Bước 2 : Bây giờ, chúng ta sẽ tạo cửa sổ hiển thị của trò chơi, tức là màn hình cửa sổ của trò chơi, nơi chúng ta sẽ tạo đầu của con rắn và thức ăn cho con rắn trong trò chơi và hiển thị điểm số ở phần đầu của trò chơi.

# Tạo một cửa sổ màn hình
wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor("blue")

# với độ rộng và độ cao là 600
wn.setup(width=600, height=600)
wn.tracer(0)

# đầu của con rắn
head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
head.direction = "Stop"

# thức ăn của con rắn
food = turtle.Turtle()
colors = random.choice(['red', 'green', 'black'])
shapes = random.choice(['square', 'triangle', 'circle'])
food.speed(0)
food.shape(shapes)
food.color(colors)
food.penup()
food.goto(0, 100)

pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 250)
pen.write("Score : 0  High Score : 0", align="center",
          font=("candara", 24, "bold"))

Kết quả ta có màn hình như sau:

Màn hình của trò chơi rắn săn mồi

Bước 3 : Bây giờ, chúng ta sẽ đăng ký các phím điều khiển hướng chuyển động của con rắn. Bằng cách nhấp vào các từ khóa thường được sử dụng để chơi game 'w', 'a', 's' và 'd', chúng ta có thể điều khiển chuyển động của con rắn xung quanh màn hình.

# đăng ký các phím điều khiển hướng
def goup():
  if head.direction != "down":
    head.direction = "up"

def godown():
  if head.direction != "up":
    head.direction = "down"

def goleft():
  if head.direction != "right":
    head.direction = "left"

def goright():
  if head.direction != "left":
    head.direction = "right"

def move():
  if head.direction == "up":
    y = head.ycor()
    head.sety(y + 20)
  if head.direction == "down":
    y = head.ycor()
    head.sety(y - 20)
  if head.direction == "left":
    x = head.xcor()
    head.setx(x - 20)
  if head.direction == "right":
    x = head.xcor()
    head.setx(x + 20)

wn.listen()
wn.onkeypress(goup, "w")
wn.onkeypress(godown, "s")
wn.onkeypress(goleft, "a")
wn.onkeypress(goright, "d")

Bước 4: Bây giờ chúng ta sẽ tạo các hiệu ứng cho những điều sau sẽ xảy ra:

  • Rắn sẽ phát triển cơ thể khi rắn ăn các loại quả.
  • Tạo màu cho đuôi rắn.
  • Sau khi ăn hết quả sẽ được tính điểm.
  • Kiểm tra đầu rắn có va chạm với thân hoặc tường của màn hình cửa sổ hay không.
  • Khởi động lại trò chơi tự động từ đầu sau khi va chạm.
  • Hình dạng và màu sắc mới của trái cây sẽ được thay đổi mỗi khi cửa sổ được khởi động lại.
  • Điểm sẽ được trả về 0 và điểm cao sẽ được giữ lại cho đến khi cửa sổ không đóng.

segments = []

# Main Gameplay
while True:
  wn.update()
  if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
    time.sleep(1)
    head.goto(0, 0)
    head.direction = "Stop"
    colors = random.choice(['red', 'blue', 'green'])
    shapes = random.choice(['square', 'circle'])
    for segment in segments:
      segment.goto(1000, 1000)
    segments.clear()
    score = 0
    delay = 0.1
    pen.clear()
    pen.write("Score : {} High Score : {} ".format(
      score, high_score), align="center", font=("candara", 24, "bold"))
  if head.distance(food) < 20:
    x = random.randint(-270, 270)
    y = random.randint(-270, 270)
    food.goto(x, y)

    # Tăng chiều dài cho rắn
    new_segment = turtle.Turtle()
    new_segment.speed(0)
    new_segment.shape("square")
    new_segment.color("orange"# tail colour
    new_segment.penup()
    segments.append(new_segment)
    delay -= 0.001
    score += 10
    if score > high_score:
      high_score = score
    pen.clear()
    pen.write("Score : {} High Score : {} ".format(
      score, high_score), align="center", font=("candara", 24, "bold"))
  # Kiểm tra va chạm giữa đầu với thân của rắn
  for index in range(len(segments) - 1, 0, -1):
    x = segments[index - 1].xcor()
    y = segments[index - 1].ycor()
    segments[index].goto(x, y)
  if len(segments) > 0:
    x = head.xcor()
    y = head.ycor()
    segments[0].goto(x, y)
  move()
  for segment in segments:
    if segment.distance(head) < 20:
      time.sleep(1)
      head.goto(0, 0)
      head.direction = "stop"
      colors = random.choice(['red', 'blue', 'green'])
      shapes = random.choice(['square', 'circle'])
      for segment in segments:
        segment.goto(1000, 1000)
      segment.clear()

      score = 0
      delay = 0.1
      pen.clear()
      pen.write("Score : {} High Score : {} ".format(
        score, high_score), align="center", font=("candara", 24, "bold"))
  time.sleep(delay)

wn.mainloop()

Dưới đây là chương trình hoàn chỉnh, chúc các bạn tạo game thành công:

# Đưa vào các module cần thiết
import turtle
import time
import random

delay = 0.1
score = 0
high_score = 0

# Tạo một cửa sổ màn hình
wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor("blue")

# với độ rộng và độ cao là 600
wn.setup(width=600, height=600)
wn.tracer(0)

# đầu của con rắn
head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
head.direction = "Stop"

# Thức ăn của rắn
food = turtle.Turtle()
colors = random.choice(['red', 'green', 'black'])
shapes = random.choice(['square', 'triangle', 'circle'])
food.speed(0)
food.shape(shapes)
food.color(colors)
food.penup()
food.goto(0, 100)

pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 250)
pen.write("Score : 0  High Score : 0", align="center",
          font=("candara", 24, "bold"))

# đăng ký các phím điều khiển hướng
def goup():
  if head.direction != "down":
    head.direction = "up"

def godown():
  if head.direction != "up":
    head.direction = "down"

def goleft():
  if head.direction != "right":
    head.direction = "left"

def goright():
  if head.direction != "left":
    head.direction = "right"

def move():
  if head.direction == "up":
    y = head.ycor()
    head.sety(y + 20)
  if head.direction == "down":
    y = head.ycor()
    head.sety(y - 20)
  if head.direction == "left":
    x = head.xcor()
    head.setx(x - 20)
  if head.direction == "right":
    x = head.xcor()
    head.setx(x + 20)

wn.listen()
wn.onkeypress(goup, "w")
wn.onkeypress(godown, "s")
wn.onkeypress(goleft, "a")
wn.onkeypress(goright, "d")

segments = []

# Main Gameplay
while True:
  wn.update()
  if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
    time.sleep(1)
    head.goto(0, 0)
    head.direction = "Stop"
    colors = random.choice(['red', 'blue', 'green'])
    shapes = random.choice(['square', 'circle'])
    for segment in segments:
      segment.goto(1000, 1000)
    segments.clear()
    score = 0
    delay = 0.1
    pen.clear()
    pen.write("Score : {} High Score : {} ".format(
      score, high_score), align="center", font=("candara", 24, "bold"))
  if head.distance(food) < 20:
    x = random.randint(-270, 270)
    y = random.randint(-270, 270)
    food.goto(x, y)

    # Tăng chiều dài cho rắn
    new_segment = turtle.Turtle()
    new_segment.speed(0)
    new_segment.shape("square")
    new_segment.color("orange"# tail colour
    new_segment.penup()
    segments.append(new_segment)
    delay -= 0.001
    score += 10
    if score > high_score:
      high_score = score
    pen.clear()
    pen.write("Score : {} High Score : {} ".format(
      score, high_score), align="center", font=("candara", 24, "bold"))
  # Kiểm tra va chạm giữa đầu với thân của rắn
 
for index in range(len(segments) - 1, 0, -1):
    x = segments[index - 1].xcor()
    y = segments[index - 1].ycor()
    segments[index].goto(x, y)
  if len(segments) > 0:
    x = head.xcor()
    y = head.ycor()
    segments[0].goto(x, y)
  move()
  for segment in segments:
    if segment.distance(head) < 20:
      time.sleep(1)
      head.goto(0, 0)
      head.direction = "stop"
      colors = random.choice(['red', 'blue', 'green'])
      shapes = random.choice(['square', 'circle'])
      for segment in segments:
        segment.goto(1000, 1000)
      segment.clear()

      score = 0
      delay = 0.1
      pen.clear()
      pen.write("Score : {} High Score : {} ".format(
        score, high_score), align="center", font=("candara", 24, "bold"))
  time.sleep(delay)

wn.mainloop()

Kết quả lập trình game Rắn săn mồi

» Tiếp: Cuộc đua Rùa với Turtle-Python
« Trước: Tách các chữ số của một số nguyên bất kỳ
Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực
Copied !!!