Skip to content

Instantly share code, notes, and snippets.

@werterhalimi
Created December 16, 2019 14:33
Show Gist options
  • Save werterhalimi/692ca9aa36552f5a52d065b15732ce12 to your computer and use it in GitHub Desktop.
Save werterhalimi/692ca9aa36552f5a52d065b15732ce12 to your computer and use it in GitHub Desktop.
The second version of my GUI snake in python using tkinter
import time
import tkinter
import random
window = tkinter.Tk()
canvas = tkinter.Canvas(window, bg="black", height=320, width=320)
window.wm_title("Press any key to start")
canvas.pack()
canvas.update()
ingame = False
positions = []
score = 0
framerate = 0.1
apple = (100, 160)
def spawnApple():
i = positions[0]
while i in positions:
i = 20 * random.randint(0, 15), 20 * random.randint(0, 15)
return i
def appendSnake():
last = snake[-1].position
action = snake[-1].action[-1]
if action == 'Left':
snake.append(Part((last[0] + 20, last[1])))
elif action == 'Right':
snake.append(Part((last[0] - 20, last[1])).move(action))
elif action == 'Up':
snake.append(Part((last[0], last[1] + 20)))
elif action == 'Down':
snake.append(Part((last[0], last[1] - 20)))
class Part:
def __init__(self, position):
self.action = []
self.position = position
positions.append(position)
def move(self, action):
self.action.append(action)
return self
def next(self):
if snake[-1] == self:
return
return snake[snake.index(self) + 1]
def execute(self):
if not self.action:
return
action = self.action[0]
positions.remove(self.position)
if action == 'Up':
self.position = (self.position[0], self.position[1] - 20)
if action == 'Down':
self.position = (self.position[0], self.position[1] + 20)
if action == 'Left':
self.position = (self.position[0] - 20, self.position[1])
if action == 'Right':
self.position = (self.position[0] + 20, self.position[1])
positions.append(self.position)
if self.next() is not None:
self.next().move(action)
if len(self.action) > 1:
self.action.remove(action)
snake = [Part((80, 20)), Part((60, 20)), Part((40, 20)), Part((20, 20)), Part((00, 20))]
def KeyboardInput(evt):
global ingame
if ingame:
snake[0].move(evt.keysym)
else:
ingame = True
snake[0].move('Right')
window.bind('<Key>', KeyboardInput)
def NewFrame():
global framerate, apple, score
canvas.delete('all')
canvas.create_rectangle(apple[0], apple[1], apple[0] + 20, apple[1] + 20, fill='red')
part = snake[0].position
if part == apple:
apple = spawnApple()
appendSnake()
score = score + 1
window.wm_title(score)
if part[0] < 0 or part[0] > 300 or part[1] < 0 or part[1] > 300 or len(positions) != len(set(positions)):
window.destory()
if ingame:
for s in snake:
s.execute()
canvas.create_rectangle(s.position[0], s.position[1], s.position[0] + 20, s.position[1] + 20, fill='white')
canvas.update()
time.sleep(framerate)
while True:
NewFrame()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment