简体   繁体   English

Python中的Snake Game Turtle图形

[英]Snake Game Turtle Graphics in Python

So I have a project where I have to create a game in TURTLE graphics only without using any other modules except turtle and the random module. 因此,我有一个项目,我只需要使用TURTLE图形创建游戏,而无需使用除了turtle和random模块之外的任何其他模块。 I am creating the traditional snake game except when the snake "eats" the object it doesn't get bigger. 我正在创建传统的蛇游戏,除了当蛇“吞噬”物体时,它不会变大。 The problem with my game is that when the "snake" gets to the object, the object does not disappear and I want it to disappear and reappear in another position. 我的游戏的问题在于,当“蛇”到达物体时,物体不会消失,而我希望它消失并重新出现在另一个位置。 Please Help. 请帮忙。 Here is the code: 这是代码:

from turtle import *
import random

setup(700, 700)
title("Snake Game!")
bgcolor("blue")

# Boundary
bPen = Pen()
bPen.color("Orange")
bPen.up()
bPen.goto(-300, -300)
bPen.down()

for i in range(4):
    bPen.ht()
    bPen.fd(600)
    bPen.lt(90)



# Player 
playerPen = Pen()
playerPen.color("Orange")
playerPen.up()
playerPen.width(4)

# Create Circle

circle = Pen()
circle.shape("circle")
circle.color("Red")
circle.up()
circle.speed(0)
circle.goto(-100, 100)



# Speed
speed = 2

# Movement functions

def left():
    playerPen.lt(90)

def right():
    playerPen.rt(90)

def speedBoost():
    global speed
    speed += 1


# Key Prompts
onkey(left, "Left")
onkey(right, "Right")
onkey(speedBoost, "Up")
listen()


# Infinity loop and player knockback
while True:
    playerPen.fd(speed)

    if playerPen.xcor() < -300 or playerPen.xcor() > 300:
        playerPen.rt(180)

    elif playerPen.ycor() < - 300 or playerPen.ycor() > 300:
        playerPen.rt(180)

    # Collision with circle
    if playerPen.xcor() == circle.xcor() and playerPen.ycor() == circle.ycor():
        circle.goto(random.randint(-300, 300), random.randint(-300, 300))


done()

The code works, but hitting the snake exactly on the center of the circle is difficult. 该代码有效,但是要精确地在圆心上打蛇是很困难的。 To fix this, at the top of your code add a constant: 要解决此问题,请在代码顶部添加一个常量:

RADIUS = 10

That is roughly the radius of the circle. 那大约是圆的半径。 Then, change this line: 然后,更改此行:

if playerPen.xcor() == circle.xcor() and playerPen.ycor() == circle.ycor():

to instead be: 相反是:

if abs(playerPen.xcor() - circle.xcor()) < RADIUS and abs(playerPen.ycor() - circle.ycor()) < RADIUS:

And enjoy the game! 享受游戏吧!

Or if you can't enjoy the game due not being able to use abs() , here's another way to write that same line without it: 或者,如果由于无法使用abs()而无法玩游戏,这是没有它的同一行的另一种写法:

if -RADIUS < playerPen.xcor() - circle.xcor() < RADIUS and -RADIUS < playerPen.ycor() - circle.ycor() < RADIUS:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM