Permainan mini Ular Python (kod sumber + komen + tampal dan gunakan) Permainan Ular ini sangat mudah dan mengelakkan penggunaan pygame yang sukar untuk dimuatkan:
Dalam melukis imej permainan, kami menggunakan pygame dalam pangkalan data Grafik Turtle yang lebih ringan
Bina pangkalan data (gamebase.py)from turtle import * # "*"是引用所有函数 def square(x, y, size, color_name): up() goto(x, y) down() color(color_name) begin_fill() forward(size) left(90) forward(size) left(90) forward(size) left(90) forward(size) left(90) end_fill()
from turtle import * from gamebase import square from random import randrange
setup(420,420,0,0) //隐藏乌龟头 emoj.emoj. hideturtle //隐藏轨迹 tracer(False) //绘制 done()
def gameLoop(): //随机生成苹果 apple_x = randrange(-200, 200) apple_y = randrange(-200, 200) //绘制苹果 square(apple_x, apple_y, 10, "red") //刷新画布 update()
def gameLoop(): //随机生成苹果 apple_x = randrange(-200, 200) apple_y = randrange(-200, 200) //绘制蛇 for n in range(len(sanke)): square(snake[n][0],snake[n][1[],10,"black) //绘制苹果 square(apple_x, apple_y, 10, "red") //刷新画布 update()
global apple_x, apple_y, snake, aim_x, aim_y #全局变量申请snake.append([ snake[-1][0] + aim_x, snake[-1][1] + aim_y ])snake.pop(0)global apple_x, apple_y, snake, aim_x, aim_y #全局变量申请 snake.append([ snake[-1][0] + aim_x, snake[-1][1] + aim_y ]) snake.pop(0)
ontimer(gameLoop, 100) # 每100毫秒运行一下gameLoop函数
listen() #监听 onkey(lambda: change(0, 10), "w") onkey(lambda: change(0, -10), "s") onkey(lambda: change(-10, 0), "a") onkey(lambda: change(10, 0), "d") gameLoop()
if snake[-1][0] != apple_x or snake[-1][1] != apple_y: snake.pop(0) else: apple_x = randrange(-20, 18) * 10 apple_y = randrange(-19, 19) * 10
def bite(): for n in range(len(snake)-1): if snake[-1][0] == snake[n][0] and snake[-1][1] == snake[n][1]: return True return False
def inside(): if -200 <= snake[-1][0] <= 180 and -190 <= snake[-1][1]<=190: return True else : return False
from turtle import * # "*"是引用所有函数 def square(x, y, size, color_name): up() goto(x, y) down() color(color_name) begin_fill() forward(size) left(90) forward(size) left(90) forward(size) left(90) forward(size) left(90) end_fill()
Atas ialah kandungan terperinci Bagaimana untuk menulis permainan Ular dalam Python?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!