- Get link
- X
- Other Apps
🧮 Simple Calculator (Python CLI)
pythondef calculator():
print("Simple Calculator")
print("Operations: +, -, *, /")
while True:
try:
num1 = float(input("Enter first number: "))
op = input("Enter operation: ")
num2 = float(input("Enter second number: "))
if op == '+':
print("Result:", num1 + num2)
elif op == '-':
print("Result:", num1 - num2)
elif op == '*':
print("Result:", num1 * num2)
elif op == '/':
if num2 == 0:
print("Cannot divide by zero.")
else:
print("Result:", num1 / num2)
else:
print("Invalid operation.")
except ValueError:
print("Invalid input.")
cont = input("Do you want to calculate again? (y/n): ")
if cont.lower() != 'y':
break
calculator()
🐍 Snake Game (Python with pygame
)
Install pygame first:
bashpip install pygame
Now the code:
pythonimport pygame
import time
import random
pygame.init()
# Screen settings
width, height = 600, 400
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")
# Colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
# Snake settings
block_size = 10
clock = pygame.time.Clock()
speed = 15
font_style = pygame.font.SysFont("bahnschrift", 25)
def message(msg, color):
mesg = font_style.render(msg, True, color)
win.blit(mesg, [width / 6, height / 3])
def gameLoop():
game_over = False
game_close = False
x, y = width / 2, height / 2
x_change = y_change = 0
snake = []
length = 1
foodx = round(random.randrange(0, width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - block_size) / 10.0) * 10.0
while not game_over:
while game_close:
win.fill(black)
message("You Lost! Press Q-Quit or C-Play Again", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
elif event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = block_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -block_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = block_size
x_change = 0
if x >= width or x < 0 or y >= height or y < 0:
game_close = True
x += x_change
y += y_change
win.fill(black)
pygame.draw.rect(win, green, [foodx, foody, block_size, block_size])
snake_head = [x, y]
snake.append(snake_head)
if len(snake) > length:
del snake[0]
for segment in snake[:-1]:
if segment == snake_head:
game_close = True
for block in snake:
pygame.draw.rect(win, white, [block[0], block[1], block_size, block_size])
pygame.display.update()
if x == foodx and y == foody:
foodx = round(random.randrange(0, width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - block_size) / 10.0) * 10.0
length += 1
clock.tick(speed)
pygame.quit()
quit()
gameLoop()
- Get link
- X
- Other Apps
Comments
Post a Comment