Snake game code using python
import pygame
import random
# Initialize Pygame
pygame.init()
# Define Colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# Set Screen Size
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Snake Game")
# Set Clock
clock = pygame.time.Clock()
# Set Font
font = pygame.font.SysFont(None, 30)
# Define Snake Function
def snake(block_size, snakeList):
for x,y in snakeList:
pygame.draw.rect(screen, black, [x, y, block_size, block_size])
# Main Game Function
def gameLoop():
# Set Game Over to False
game_over = False
# Set Direction
direction = "right"
# Set Block Size
block_size = 10
# Set Speed
speed = 15
# Set Food Position
food_x = round(random.randrange(0, screen_width-block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height-block_size) / 10.0) * 10.0
# Set Initial Snake Position
snakeList = []
snakeLength = 1
x = screen_width / 2
y = screen_height / 2
# Main Loop
while not game_over:
# Event Loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# Set Direction Based on Arrow Keys
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
direction = "left"
if event.key == pygame.K_RIGHT:
direction = "right"
if event.key == pygame.K_UP:
direction = "up"
if event.key == pygame.K_DOWN:
direction = "down"
# Move Snake
if direction == "right":
x += block_size
elif direction == "left":
x -= block_size
elif direction == "up":
y -= block_size
elif direction == "down":
y += block_size
# Draw Background
screen.fill(white)
# Draw Food
pygame.draw.rect(screen, red, [food_x, food_y, block_size, block_size])
# Update Snake
snakeHead = []
snakeHead.append(x)
snakeHead.append(y)
snakeList.append(snakeHead)
if len(snakeList) > snakeLength:
del snakeList[0]
# Check for Game Over
for eachSegment in snakeList[:-1]:
if eachSegment == snakeHead:
game_over = True
# Draw Snake
snake(block_size, snakeList)
# Update Score
score = font.render("Score: " + str(snakeLength-1), True, black)
screen.blit(score, [0, 0])
# Update Display
pygame.display.update()
# Check for Food Collision
if x == food_x and y == food_y:
food_x = round(random.randrange(0, screen_width-block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height-block_size) / 10.0) * 10.0
snakeLength += 1
# Set Game Speed
clock.tick(speed)
# Quit Pygame
pygame.quit()
# Run Game
gameLoop()
Rock Paper Scissor and Paper game using Python and phpHere is a simple implementation of the Snake game using Python and the Pygame module:
Code:import pygame import random # Initialize Pygame pygame.init() # Define Colors white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) # Set Screen Size screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Snake Game") # Set Clock clock = pygame.time.Clock() # Set Font font = pygame.font.SysFont(None, 30) # Define Snake Function def snake(block_size, snakeList): for x,y in snakeList: pygame.draw.rect(screen, black, [x, y, block_size, block_size]) # Main Game Function def gameLoop(): # Set Game Over to False game_over = False # Set Direction direction = "right" # Set Block Size block_size = 10 # Set Speed speed = 15 # Set Food Position food_x = round(random.randrange(0, screen_width-block_size) / 10.0) * 10.0 food_y = round(random.randrange(0, screen_height-block_size) / 10.0) * 10.0 # Set Initial Snake Position snakeList = [] snakeLength = 1 x = screen_width / 2 y = screen_height / 2 # Main Loop while not game_over: # Event Loop for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True # Set Direction Based on Arrow Keys if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: direction = "left" if event.key == pygame.K_RIGHT: direction = "right" if event.key == pygame.K_UP: direction = "up" if event.key == pygame.K_DOWN: direction = "down" # Move Snake if direction == "right": x += block_size elif direction == "left": x -= block_size elif direction == "up": y -= block_size elif direction == "down": y += block_size # Draw Background screen.fill(white) # Draw Food pygame.draw.rect(screen, red, [food_x, food_y, block_size, block_size]) # Update Snake snakeHead = [] snakeHead.append(x) snakeHead.append(y) snakeList.append(snakeHead) if len(snakeList) > snakeLength: del snakeList[0] # Check for Game Over for eachSegment in snakeList[:-1]: if eachSegment == snakeHead: game_over = True # Draw Snake snake(block_size, snakeList) # Update Score score = font.render("Score: " + str(snakeLength-1), True, black) screen.blit(score, [0, 0]) # Update Display pygame.display.update() # Check for Food Collision if x == food_x and y == food_y: food_x = round(random.randrange(0, screen_width-block_size) / 10.0) * 10.0 food_y = round(random.randrange(0, screen_height-block_size) / 10.0) * 10.0 snakeLength += 1 # Set Game Speed clock.tick(speed) # Quit Pygame pygame.quit() # Run Game gameLoop()
This code creates a simple game with a snake that grows as it eats food and ends when it collides with itself. It also displays the score on the screen. Feel free to modify the code to suit your needs and add additional features.
How about mathematics games code using pythonHere is a simple implementation of the Snake game using Python and the Pygame module:
Code:import pygame import random # Initialize Pygame pygame.init() # Define Colors white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) # Set Screen Size screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Snake Game") # Set Clock clock = pygame.time.Clock() # Set Font font = pygame.font.SysFont(None, 30) # Define Snake Function def snake(block_size, snakeList): for x,y in snakeList: pygame.draw.rect(screen, black, [x, y, block_size, block_size]) # Main Game Function def gameLoop(): # Set Game Over to False game_over = False # Set Direction direction = "right" # Set Block Size block_size = 10 # Set Speed speed = 15 # Set Food Position food_x = round(random.randrange(0, screen_width-block_size) / 10.0) * 10.0 food_y = round(random.randrange(0, screen_height-block_size) / 10.0) * 10.0 # Set Initial Snake Position snakeList = [] snakeLength = 1 x = screen_width / 2 y = screen_height / 2 # Main Loop while not game_over: # Event Loop for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True # Set Direction Based on Arrow Keys if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: direction = "left" if event.key == pygame.K_RIGHT: direction = "right" if event.key == pygame.K_UP: direction = "up" if event.key == pygame.K_DOWN: direction = "down" # Move Snake if direction == "right": x += block_size elif direction == "left": x -= block_size elif direction == "up": y -= block_size elif direction == "down": y += block_size # Draw Background screen.fill(white) # Draw Food pygame.draw.rect(screen, red, [food_x, food_y, block_size, block_size]) # Update Snake snakeHead = [] snakeHead.append(x) snakeHead.append(y) snakeList.append(snakeHead) if len(snakeList) > snakeLength: del snakeList[0] # Check for Game Over for eachSegment in snakeList[:-1]: if eachSegment == snakeHead: game_over = True # Draw Snake snake(block_size, snakeList) # Update Score score = font.render("Score: " + str(snakeLength-1), True, black) screen.blit(score, [0, 0]) # Update Display pygame.display.update() # Check for Food Collision if x == food_x and y == food_y: food_x = round(random.randrange(0, screen_width-block_size) / 10.0) * 10.0 food_y = round(random.randrange(0, screen_height-block_size) / 10.0) * 10.0 snakeLength += 1 # Set Game Speed clock.tick(speed) # Quit Pygame pygame.quit() # Run Game gameLoop()
This code creates a simple game with a snake that grows as it eats food and ends when it collides with itself. It also displays the score on the screen. Feel free to modify the code to suit your needs and add additional features.
Here is a simple implementation of the Rock Paper Scissors game using Python:Rock Paper Scissor and Paper game using Python and php
import random
# Define Options
options = ["rock", "paper", "scissors"]
# Main Game Loop
while True:
# Get Player Choice
player_choice = input("Choose [rock/paper/scissors]: ")
# Check for Valid Choice
if player_choice not in options:
print("Invalid choice. Please try again.")
continue
# Get Computer Choice
computer_choice = random.choice(options)
print("Computer chooses", computer_choice)
# Determine Winner
if player_choice == computer_choice:
print("Tie!")
elif player_choice == "rock" and computer_choice == "scissors":
print("You win!")
elif player_choice == "scissors" and computer_choice == "paper":
print("You win!")
elif player_choice == "paper" and computer_choice == "rock":
print("You win!")
else:
print("Computer wins!")
# Ask to Play Again
play_again = input("Play again? [y/n]: ")
if play_again == "n":
break
Here is an example of a simple math game in Python:How about mathematics games code using python
import random
# Define Game Function
def mathGame():
# Set Score to 0
score = 0
# Main Loop
while True:
# Generate Random Numbers
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
# Get User Input
answer = input(f"What is {num1} + {num2}? ")
# Check Answer
if int(answer) == num1 + num2:
print("Correct!")
score += 1
else:
print(f"Incorrect! The answer was {num1+num2}")
# Display Score
print(f"Score: {score}")
# Ask User if They Want to Continue Playing
play_again = input("Do you want to play again? (y/n) ")
if play_again.lower() == "n":
break
# Run Game
mathGame()
Another math game code using pythonHere is an example of a simple math game in Python:
Code:import random # Define Game Function def mathGame(): # Set Score to 0 score = 0 # Main Loop while True: # Generate Random Numbers num1 = random.randint(1, 10) num2 = random.randint(1, 10) # Get User Input answer = input(f"What is {num1} + {num2}? ") # Check Answer if int(answer) == num1 + num2: print("Correct!") score += 1 else: print(f"Incorrect! The answer was {num1+num2}") # Display Score print(f"Score: {score}") # Ask User if They Want to Continue Playing play_again = input("Do you want to play again? (y/n) ") if play_again.lower() == "n": break # Run Game mathGame()
This code generates two random numbers between 1 and 10 and asks the user to solve their sum. It then checks the user's answer and updates their score accordingly. The game continues until the user decides to stop playing.
You can modify the code to include other operations like subtraction, multiplication, or division, and to adjust the range of the numbers generated.
Sure! Here's an example of a math game that generates random addition, subtraction, multiplication or division problems:Another math game code using python
import random
# Define Game Function
def mathGame():
# Set Score to 0
score = 0
# Main Loop
while True:
# Generate Random Numbers and Operation
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
op = random.choice(["+", "-", "*", "/"])
if op == "/" and num2 == 0:
num2 = 1
# Get User Input
problem = f"What is {num1} {op} {num2}? "
answer = input(problem)
# Check Answer
if op == "+":
correct_answer = num1 + num2
elif op