Tic Tac Toe
Source Code
import turtle
# getting a Screen to work on
ws=turtle.Screen()
# Defining Turtle instance
t=turtle.Turtle()
# setting up turtle color to green
t.color("Green")
# Setting Up width to 2
t.width("2")
# Setting up speed to 2
t.speed(2)
# Loop for making outside square of
# length 300
for i in range(4):
t.forward(300)
t.left(90)
# code for inner lines of the square
t.penup()
t.goto(0,100)
t.pendown()
t.forward(300)
t.penup()
t.goto(0,200)
t.pendown()
t.forward(300)
t.penup()
t.goto(100,0)
t.pendown()
t.left(90)
t.forward(300)
t.penup()
t.goto(200,0)
t.pendown()
t.forward(300)
SNAKE
Source Code
from tkinter import *
import random
GAME_WIDTH = 700
GAME_HEIGHT = 700
SPEED = 100
SPACE_SIZE = 50
BODY_PARTS = 3
SNAKE_COLOR = "#00FF00"
FOOD_COLOR = "#FF0000"
BACKGROUND_COLOR = "#000000"
class Snake:
def __init__(self):
self.body_size = BODY_PARTS
self.coordinates = []
self.squares = []
for i in range(0, BODY_PARTS):
self.coordinates.append([0, 0])
for x, y in self.coordinates:
square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR, tag="snake")
self.squares.append(square)
class Food:
def __init__(self):
x = random.randint(0, (GAME_WIDTH / SPACE_SIZE)-1) * SPACE_SIZE
y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE) - 1) * SPACE_SIZE
self.coordinates = [x, y]
canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag="food")
def next_turn(snake, food):
x, y = snake.coordinates[0]
if direction == "up":
y -= SPACE_SIZE
elif direction == "down":
y += SPACE_SIZE
elif direction == "left":
x -= SPACE_SIZE
elif direction == "right":
x += SPACE_SIZE
snake.coordinates.insert(0, (x, y))
square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR)
snake.squares.insert(0, square)
if x == food.coordinates[0] and y == food.coordinates[1]:
global score
score += 1
label.config(text="Score:{}".format(score))
canvas.delete("food")
food = Food()
else:
del snake.coordinates[-1]
canvas.delete(snake.squares[-1])
del snake.squares[-1]
if check_collisions(snake):
game_over()
else:
window.after(SPEED, next_turn, snake, food)
def change_direction(new_direction):
global direction
if new_direction == 'left':
if direction != 'right':
direction = new_direction
elif new_direction == 'right':
if direction != 'left':
direction = new_direction
elif new_direction == 'up':
if direction != 'down':
direction = new_direction
elif new_direction == 'down':
if direction != 'up':
direction = new_direction
def check_collisions(snake):
x, y = snake.coordinates[0]
if x < 0 or x >= GAME_WIDTH:
return True
elif y < 0 or y >= GAME_HEIGHT:
return True
for body_part in snake.coordinates[1:]:
if x == body_part[0] and y == body_part[1]:
return True
return False
def game_over():
canvas.delete(ALL)
canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2,
font=('consolas',70), text="GAME OVER", fill="red", tag="gameover")
window = Tk()
window.title("Snake game")
window.resizable(False, False)
score = 0
direction = 'down'
label = Label(window, text="Score:{}".format(score), font=('consolas', 40))
label.pack()
canvas = Canvas(window, bg=BACKGROUND_COLOR, height=GAME_HEIGHT, width=GAME_WIDTH)
canvas.pack()
window.update()
window_width = window.winfo_width()
window_height = window.winfo_height()
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x = int((screen_width/2) - (window_width/2))
y = int((screen_height/2) - (window_height/2))
window.geometry(f"{window_width}x{window_height}+{x}+{y}")
window.bind('', lambda event: change_direction('left'))
window.bind('', lambda event: change_direction('right'))
window.bind('', lambda event: change_direction('up'))
window.bind('', lambda event: change_direction('down'))
snake = Snake()
food = Food()
next_turn(snake, food)
window.mainloop()
PING PONG
preSource Code
import turtle
import winsound
# Window properties
win = turtle.Screen()
win.title('Pong')
win.bgcolor('green')
win.setup(width=800,height=600)
win.tracer(0)
def drawField():
draw = turtle.Turtle()
draw.penup()
draw.speed(0)
draw.color('white')
draw.hideturtle()
draw.goto(-390,295)
draw.pendown()
for i in range(2):
draw.forward(770)
draw.right(90)
draw.forward(580)
draw.right(90)
draw.goto(0,295)
draw.right(90)
draw.goto(0,-285)
draw.penup()
draw.goto(-50,0)
draw.pendown()
draw.circle(50)
drawField()
# Scores
scoreA = 0
scoreB = 0
# Paddle A
padA = turtle.Turtle()
padA.speed(0)
padA.shape('square')
padA.shapesize(stretch_wid=6,stretch_len=1)
padA.color('white')
padA.penup()
padA.goto(-350,0)
# Paddle B
padB = turtle.Turtle()
padB.speed(0)
padB.shape('square')
padB.shapesize(stretch_wid=6,stretch_len=1)
padB.color('white')
padB.penup()
padB.goto(350,0)
# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape('circle')
ball.color('white')
ball.penup()
ball.goto(0,0)
ball.dx = 1.0
ball.dy = 1.0
# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.color('white')
pen.penup()
pen.hideturtle()
pen.goto(0,250)
# Functions :
def padA_up():
y = padA.ycor()
y += 25
padA.sety(y)
def padA_down():
y = padA.ycor()
y -= 25
padA.sety(y)
def padB_up():
y = padB.ycor()
y += 25
padB.sety(y)
def padB_down():
y = padB.ycor()
y -= 25
padB.sety(y)
def write():
pen.write(f"Player A : {scoreA} Player B : {scoreB}",align='center',font=('Courier',24,'normal'))
def playMusic(music):
try:
winsound.PlaySound(music, winsound.SND_ASYNC)
except FileNotFoundError:
print('The required music file does not exist.')
except:
print('winsound module only works on windows.')
print('try playing the sound with os module')
# Keyboard bindings
win.listen()
win.onkeypress(padA_up,'w')
win.onkeypress(padA_down,'s')
win.onkeypress(padB_up,'Up')
win.onkeypress(padB_down,'Down')
write()
# * ------------------------------------------------------------ *
# Main game loop
try:
while True:
win.update()
# Moving the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border collison
if ball.ycor() > 290:
ball.dy *= -1
playMusic('assets/hit1.wav')
if ball.ycor() < -290:
ball.dy *= -1
playMusic('assets/hit1.wav')
if ball.xcor() > 390:
ball.setx(-100)
ball.dx *= -1
scoreA += 1
pen.clear()
write()
if ball.xcor() < -390:
ball.setx(-100)
ball.dx *= -1
scoreB += 1
pen.clear()
write()
# Paddle and ball collision
if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < padB.ycor() + 50 and ball.ycor() > padB.ycor() - 50):
playMusic('assets/hit2.wav')
ball.setx(340)
ball.dx *= -1
if (ball.xcor() < -340 and ball.xcor() >-350) and (ball.ycor() < padA.ycor() + 50 and ball.ycor() > padA.ycor() - 50):
playMusic('assets/hit2.wav')
ball.setx(-340)
ball.dx *= -1
except Exception as e:
pass