This tab is for code that is free to use, be it in GDscript to GML. you can use it for any projects you need.
There's also some that are just full games! to play them, just put them into an IDE for the respective language.
github link: https://github.com/Rouzyoqi/Rouzyoqi/tree/main
Free to use Python code:
import random
import sys
import os
# message to modders: Hello, If you are here to mod the game, here are some guidelines you should follow:
# 1. to not break the code, don't touch things that are labled as VIDT this means "Very Important Don't Touch"
# 2. do not try to use chatgpt to just rewrite it, this is highly personal code. Chatgpt might have a stroke trying to read this
# 3. have fun and learn, I made this game in a week and it took a lot of effort to get working. I've posted the sourcecode for people to learn and grow as programmers.
# Main variables
day = 0
quota = random.randint(200, 350)
starting_cash = random.randint(50, 150)
shop_inv = []
trading_ship_lvl = 0
buying_stock = ['Alcohol', 'Tea', 'Salt', 'Fine China', 'Textiles']
unlockable_stock = ['Weapons', 'Tin', 'Gold', 'Rice', 'Opium', 'Sugar']
unlockable_prices = [20, 30, 90, 8, 15, 23]
unlockables_obtained = []
stock_prices = [5, 7, 1, 50, 10]
player_money = starting_cash
# Random name data
rnf = ['Aiman', 'Nurul', 'Syafiq', 'Farah', 'Amirul', 'Arjun', 'Priya', 'Ravi', 'Ananya', 'Kiran',
'Zhang', 'Chen', 'Wang', 'Huang', 'James', 'Emily', 'Oliver', 'Charlotte', 'Daniel', 'Sans'] # random first names
rnl = ['Hakim', 'Izzah', 'Rahman', 'Nadia', 'Faiz', 'Patel', 'Sharma', 'Kumar', 'Hamiz', 'Mehta',
'Mei', 'Jia Hao', 'Li Na', 'Zhen', 'Taylor', 'Clarke', 'Smith', 'Brown', 'Evans', 'Papyrus'] # random last names
dfb = ['really wants', 'wants to buy', 'haggles for', 'wants you to sell them', 'wants'] # dialogues for buying
dfi = ['Hi, my name is', 'The name\'s', 'Hello sir, my name is', 'Hey, my name is', 'Let me introduce myself, I am'] # dialogues for introducing
dfbo = ['don\'t talk to me, I\'m busy', 'I heard people were getting robbed here! Best to be careful...',
'I heard the nasi lemak here was amazing!', 'Shut up you dolt! I\'m trying to browse',
'And erm, do you have any spices?', 'Are you going to the mosque tomorrow?', 'You will adopt a kitten in 65 days', 'Nyehehe'] # dialogues for the body of a conversation
# Pause function
def pause():
input("Press ENTER to continue...\n")
# Stock purchasing
def stock_choices(money):
print("\n-- Buying Stock --")
print("Which stock do you buy?:")
for i, item in enumerate(buying_stock):
print(f" {i+1}. {item}: RM {stock_prices[i]}")
try:
stock_choice = int(input("Please pick a product: ")) - 1
if 0 <= stock_choice < len(buying_stock):
price = stock_prices[stock_choice]
if money >= price:
chosen_item = buying_stock[stock_choice]
shop_inv.append(chosen_item)
money -= price
print(f"You bought: {chosen_item}")
print(f"Current shop inventory: {shop_inv}")
else:
print("You don't have enough money for that.")
else:
print("Invalid choice.")
except ValueError:
print("Please enter a valid number.")
return money
def shop_upgrades(shipping_lvl, player_money, buying_stock, unlockable_stock, stock_prices, unlockable_prices):
print("\n-- Shop Upgrades -- \nWhat upgrades do you want?")
print(" 1. Shipping level 1, unlockables: Weapons, Tin (RM 40)")
print(" 2. Shipping level 2, unlockables: Gold, Rice (RM 100)")
print(" 3. Shipping level 3, unlockables: Opium, Sugar (RM 160)")
try:
unlocking = int(input("Please choose a shipping level to unlock (1/2/3): "))
except ValueError:
print("Invalid input. Please enter a number (1, 2, or 3).")
return shipping_lvl, player_money, buying_stock, stock_prices
# Unlocking level 1
if unlocking == 1 and shipping_lvl < 1 and player_money >= 40:
player_money -= 40
shipping_lvl = 1
print("Level 1 shipping is open, you can now sell: Weapons & Tin")
buying_stock.extend([unlockable_stock[0], unlockable_stock[1]]) # Add Weapons & Tin
stock_prices.extend([unlockable_prices[0], unlockable_prices[1]]) # Add prices for Weapons & Tin
# Unlocking level 2
elif unlocking == 2 and shipping_lvl >= 1 and shipping_lvl < 2 and player_money >= 100:
player_money -= 100
shipping_lvl = 2
print("Level 2 shipping is open, you can now sell: Gold & Rice")
buying_stock.extend([unlockable_stock[2], unlockable_stock[3]]) # Add Gold & Rice
stock_prices.extend([unlockable_prices[2], unlockable_prices[3]]) # Add prices for Gold & Rice
# Unlocking level 3
elif unlocking == 3 and shipping_lvl >= 2 and shipping_lvl < 3 and player_money >= 160:
player_money -= 160
shipping_lvl = 3
print("Highest shipping level obtained! You can now sell: Opium & Sugar")
buying_stock.extend([unlockable_stock[4], unlockable_stock[5]]) # Add Opium & Sugar
stock_prices.extend([unlockable_prices[4], unlockable_prices[5]]) # Add prices for Opium & Sugar
# Invalid or already unlocked level
else:
print("Invalid choice, you either don't have enough money, or you've already unlocked this level.")
return shipping_lvl, player_money, buying_stock, stock_prices
# Customer interaction
def customer_engine(money):
print("\n-- Customer Menu --")
print("1. Talk to customers\n2. Tend to buyers\n3. Tell everyone to GET OUT!")
try:
choice = int(input("Choose an option: "))
if choice == 1:
print("You look for a customer to talk to...")
pause()
print("You find someone!")
pause()
print(f"Person: {random.choice(dfi)} {random.choice(rnf)} {random.choice(rnl)} — {random.choice(dfbo)}")
pause()
elif choice == 2:
if not shop_inv:
print("Your shop is empty! No one can buy anything.")
return money
pause()
item = random.choice(shop_inv)
print(f"{random.choice(rnf)} {random.choice(rnl)} {random.choice(dfb)} {item}.")
try:
sell = int(input(f"Sell them {item}? (1 = Yes / 2 = No): "))
if sell == 1:
shop_inv.remove(item)
gain = stock_prices[buying_stock.index(item)] + random.randint(10, 23)
print(f"You sold {item} and earned RM {gain}.")
money += gain
else:
print("You declined the sale. The customer leaves.")
except ValueError:
print("Invalid input.")
elif choice == 3:
print("You yell for everyone to leave. The shop empties out.")
else:
print("Invalid choice.")
except ValueError:
print("Invalid input.")
return money
# Advance the day
def day_advance(current_day, money):
current_day += 1
print("You advance to the next day...")
pause()
tax_change = random.randint(-30, 50)
money += tax_change
if tax_change > 0:
print(f"You got RM {tax_change} from the tax man.")
elif tax_change < 0:
print(f"You were taxed RM {-tax_change}.")
else:
print("The tax man didn't show up today.")
return current_day, money
# Game intro
def opening():
print("Welcome to *The Merchant*, a game of finance and money management.")
pause()
print("Inspired by *The Oregon Trail*, you are a merchant in 1800s Pulau Pinang.")
pause()
print(f"Your quota to return home is: RM {quota}")
pause()
print(f"You start with RM {starting_cash}. Good luck!")
pause()
# Game loop
def gameloop():
global player_money, day, trading_ship_lvl
shop_size = 6
while True:
print(f"\nDay: {day} | Quota: RM {quota} | Money: RM {player_money}")
print("-- Player Menu --")
print("1. Buy stock\n2. Check Stats\n3. Tend to customers\n4. Advance day \n5. Upgrade shop\n6. Help")
try:
choice = int(input("What will you do?: "))
if player_money <= 0:
print(f"You went bankrupt on day {day}. Game over.")
break
if player_money >= quota:
print(f"You reached your quota of RM {quota} in {day} days! Well done!")
print("Check out more games at https://rouzyoqi.itch.io/")
print("Would you like to start a new run?: (Y = 1 / N = 2)")
restart_game = int(input("awaiting command...: "))
if choice == 1:
player_money = stock_choices(player_money)
elif choice == 2:
pause()
print("-- PLAYER STATS --","\nYour shop inventory:", shop_inv, "\nYour bank account: ", player_money, "\nDay number: ", day, "\nShipping Level: ", trading_ship_lvl)
elif choice == 3:
player_money = customer_engine(player_money)
elif choice == 4:
day, player_money = day_advance(day, player_money)
elif choice == 5:
shop_upgrades(trading_ship_lvl, player_money, buying_stock, unlockable_stock, stock_prices, unlockable_prices)
elif choice == 6:
print("1. Buy stock to grow your inventory.")
print("2. Check your game stats.")
print("3. Interact with or sell to customers.")
print("4. Advance the day, but taxes may affect your cash!")
print("5. Upgrade your shop to allow you to sell more items")
print("6. open this menu")
else:
print("Please choose a valid option.")
except ValueError:
print("Enter a number.")
# Title screen
def Start():
print("-- The Merchant --")
print("1. Play\n2. Credits\n3. Quit")
try:
menu_choice = int(input("Choose an option: "))
if menu_choice == 1:
opening()
gameloop()
elif menu_choice == 2:
print("Programming: Rouzyoqi")
print("Check out more of my stuff: https://rouzyoqi.itch.io/")
elif menu_choice == 3:
sys.exit("Goodbye!")
else:
print("Invalid choice.")
except ValueError:
print("Please enter a number.")
# Start the game
Start()
def binary_to_decimal(binary):
return int(binary, 2)
def decimal_to_binary(decimal):
return bin(int(decimal))[2:]
def hex_to_decimal(hexadecimal):
return int(hexadecimal, 16)
def decimal_to_hex(decimal):
return hex(int(decimal))[2:]
def string_to_binary(text):
return ' '.join(format(ord(char), '08b') for char in text)
def binary_to_string(binary):
chars = binary.split()
return ''.join(chr(int(char, 2)) for char in chars)
def string_to_hex(text):
return ' '.join(format(ord(char), 'x') for char in text)
def hex_to_string(hex_str):
chars = hex_str.split()
return ''.join(chr(int(char, 16)) for char in chars)
def menu():
while True:
print("\n--- Converter ---")
print("1. Binary to Decimal / String")
print("2. Decimal to Binary / Hex")
print("3. Hex to Decimal / String")
print("4. String to Binary / Hex")
print("5. Quit")
choice = input("Choose an option (1-5): ")
if choice == "1":
binary = input("Enter binary (e.g., 01001000 01101001): ")
try:
print("Decimal:", binary_to_decimal(binary.replace(" ", "")))
print("String:", binary_to_string(binary))
except:
print("Invalid binary input.")
elif choice == "2":
decimal = input("Enter decimal: ")
try:
print("Binary:", decimal_to_binary(decimal))
print("Hex:", decimal_to_hex(decimal))
except:
print("Invalid decimal input.")
elif choice == "3":
hex_value = input("Enter hexadecimal (e.g., 48 69): ")
try:
print("Decimal:", hex_to_decimal(hex_value.replace(" ", "")))
print("String:", hex_to_string(hex_value))
except:
print("Invalid hex input.")
elif choice == "4":
text = input("Enter string: ")
print("Binary:", string_to_binary(text))
print("Hex:", string_to_hex(text))
elif choice == "5":
print("Goodbye!")
break
else:
print("Invalid option.")
if __name__ == "__main__":
menu()
import random
# Dice Rolling
def roll_dice(sides=20):
return random.randint(1, sides)
# Notes
notes = []
def add_note(note):
notes.append(note)
def view_notes():
return notes
# Player & Party Management
party = {}
CLASSES = ["Wizard", "Paladin", "Warlock", "Rogue", "Cleric", "Druid", "Fighter", "Ranger", "Bard", "Barbarian"]
RACES = ["Human", "Elf", "Elfling", "Dwarf", "Ogre", "Orc", "Half-Orc", "Animagus", "Half-Anima"]
STAT_NAMES = ["Strength", "Magic", "Intelligence", "Dexterity", "Speed"]
def create_player():
name = input("Enter player name: ")
print("Choose a class:")
for idx, c in enumerate(CLASSES, 1):
print(f"{idx}. {c}")
player_class = CLASSES[int(input("Enter number: ")) - 1]
print("Choose a race:")
for idx, r in enumerate(RACES, 1):
print(f"{idx}. {r}")
player_race = RACES[int(input("Enter number: ")) - 1]
# Distribute 10 points across stats
stats = {stat: 0 for stat in STAT_NAMES}
points_left = 10
while points_left > 0:
print(f"Distribute {points_left} points across your stats:")
for idx, stat in enumerate(STAT_NAMES, 1):
print(f"{idx}. {stat}: {stats[STAT_NAMES[idx-1]]}")
stat_choice = int(input(f"Choose a stat to add points to (1-{len(STAT_NAMES)}): ")) - 1
if points_left > 0:
points_to_add = int(input(f"How many points to add to {STAT_NAMES[stat_choice]}? (Remaining points: {points_left}): "))
if points_to_add <= points_left:
stats[STAT_NAMES[stat_choice]] += points_to_add
points_left -= points_to_add
else:
print("You don't have enough points to add that many!")
else:
print("You must distribute all points!")
spells = []
inventory = []
party[name] = {
"Class": player_class,
"Race": player_race,
"Stats": stats,
"HP": 50,
"Spells": spells,
"Inventory": inventory
}
print(f"{name} created with class {player_class} and race {player_race}.")
print(f"Stats: {stats}")
def view_party():
return party
def update_hp(name, amount):
if name in party:
party[name]["HP"] += amount
party[name]["HP"] = max(0, min(party[name]["HP"], 50))
print(f"{name}'s HP updated to {party[name]['HP']}.")
def set_stat(name, stat, value):
if name in party and stat in party[name]["Stats"]:
party[name]["Stats"][stat] = value
print(f"{name}'s {stat} set to {value}.")
def check_inventory(name):
if name in party:
return party[name]["Inventory"]
return None
def add_item(name, item, type_, value):
if name in party and len(party[name]["Inventory"]) < 10:
party[name]["Inventory"].append({"Name": item, "Type": type_, "Value": value})
print(f"{item} added to {name}'s inventory.")
def remove_item(name, item):
if name in party:
inv = party[name]["Inventory"]
for i in inv:
if i["Name"] == item:
inv.remove(i)
print(f"{item} removed from {name}'s inventory.")
return
print(f"{item} not found in inventory.")
def add_spell(name, spell, damage):
if name in party and len(party[name]["Spells"]) < 5:
party[name]["Spells"].append({"Name": spell, "Damage": damage})
print(f"Spell {spell} added.")
def view_spells(name):
if name in party:
return party[name]["Spells"]
# NPC Creator
npc_list = []
def create_npc():
name = input("Enter NPC name: ")
role = input("Enter NPC role: ")
quirk = input("Enter NPC quirk or notable feature: ")
npc = {
"Name": name,
"Role": role,
"Quirk": quirk
}
npc_list.append(npc)
print("NPC created.")
return npc
def view_npcs():
if not npc_list:
print("No NPCs created.")
else:
for i, npc in enumerate(npc_list):
print(f"{i+1}. {npc}")
# Quest System
quests = []
def create_quest():
if not npc_list:
print("No NPCs created yet. Please create an NPC first.")
return
print("Choose an NPC for the quest:")
for idx, npc in enumerate(npc_list, 1):
print(f"{idx}. {npc['Name']} - {npc['Role']}")
npc_choice = int(input("Enter number of NPC: ")) - 1
npc = npc_list[npc_choice]
objective = input("Enter quest objective (e.g., Retrieve artifact, Defeat enemy, Escort NPC, Explore dungeon): ")
reward = input("Enter reward (e.g., Gold, Magic Item, Information, Favor): ")
quest = {
"NPC": npc,
"Objective": objective,
"Reward": reward
}
quests.append(quest)
print(f"Quest created: {npc['Name']} wants you to {objective.lower()} for {reward.lower()}.")
def view_quests():
if not quests:
print("No quests yet.")
else:
for i, q in enumerate(quests):
print(f"{i+1}. NPC: {q['NPC']['Name']} | Objective: {q['Objective']} | Reward: {q['Reward']}")
# Enemy Moveset
enemy_movesets = {}
def create_enemy_moveset():
name = input("Enter enemy name: ")
moves = []
while True:
move = input("Enter move (or type 'done'): ")
if move.lower() == 'done':
break
moves.append(move)
enemy_movesets[name] = moves
print(f"Moveset for {name} saved.")
def view_enemy_moveset():
if not enemy_movesets:
print("No enemy movesets.")
else:
for enemy, moves in enemy_movesets.items():
print(f"{enemy}: {', '.join(moves)}")
# Fight Tracker
def damage_player():
name = input("Enter player name to damage: ")
amount = int(input("Enter damage amount: "))
update_hp(name, -amount)
def heal_player():
name = input("Enter player name to heal: ")
amount = int(input("Enter heal amount: "))
update_hp(name, amount)
# Main Menu
def main():
while True:
print("\n-- DnD Campaign Manager --")
print("1. Roll Dice")
print("2. Create Player / View Party")
print("3. Manage Inventory / Spells")
print("4. Add/View Notes")
print("5. Quest Creator")
print("6. Create/View NPCs")
print("7. Enemy Movesets")
print("8. Fight Management")
print("9. Change Player Stats")
print("10. Quit")
choice = input("Choose an option: ")
if choice == "1":
sides = input("Enter number of sides (default 20): ")
result = roll_dice(int(sides) if sides.isdigit() else 20)
print(f"Rolled: {result}")
elif choice == "2":
sub = input("Create or View party? (c/v): ").lower()
if sub == 'c':
create_player()
elif sub == 'v':
print(view_party())
elif choice == "3":
name = input("Enter player name: ")
action = input("Add Item (a), Remove Item (r), View Inventory (v), Add Spell (s), View Spells (sp): ").lower()
if action == 'a':
item = input("Enter item name: ")
type_ = input("Is it a weapon or usable?: ").lower()
value = input("Enter value (e.g., damage or quantity): ")
add_item(name, item, type_, value)
elif action == 'r':
item = input("Enter item to remove: ")
remove_item(name, item)
elif action == 'v':
print(check_inventory(name))
elif action == 's':
spell = input("Enter spell name: ")
dmg = input("Enter damage: ")
add_spell(name, spell, dmg)
elif action == 'sp':
print(view_spells(name))
elif choice == "4":
sub = input("Add or View notes? (a/v): ").lower()
if sub == 'a':
note = input("Enter note: ")
add_note(note)
elif sub == 'v':
print("Notes:")
for n in view_notes():
print(f"- {n}")
elif choice == "5":
sub = input("Create or View quests? (c/v): ").lower()
if sub == 'c':
create_quest()
elif sub == 'v':
view_quests()
elif choice == "6":
sub = input("Create or View NPCs? (c/v): ").lower()
if sub == 'c':
create_npc()
elif sub == 'v':
view_npcs()
elif choice == "7":
sub = input("Create or View enemy moveset? (c/v): ").lower()
if sub == 'c':
create_enemy_moveset()
elif sub == 'v':
view_enemy_moveset()
elif choice == "8":
action = input("Damage or Heal player? (d/h): ").lower()
if action == 'd':
damage_player()
elif action == 'h':
heal_player()
elif choice == "9":
name = input("Enter player name: ")
stat = input("Enter stat to change: ")
value = int(input("Enter new value: "))
set_stat(name, stat, value)
elif choice == "10":
print("Good luck on your campaign!")
break
else:
print("Invalid choice.")
if __name__ == "__main__":
main()
import random
# Card setup
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = {
'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,
'8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10, 'A': 11
}
# Create and shuffle the deck
def create_deck():
deck = [(rank, suit) for rank in ranks for suit in suits]
random.shuffle(deck)
return deck
# Calculate hand value with Ace adjustments
def calculate_hand(hand):
value = sum(ranks[card[0]] for card in hand)
aces = sum(1 for card in hand if card[0] == 'A')
while value > 21 and aces:
value -= 10
aces -= 1
return value
# Display hand
def display_hand(hand, hidden=False):
if hidden:
print("Dealer's hand: [?,", f"{hand[1][0]} of {hand[1][1]}]")
else:
print("Hand:", ", ".join(f"{rank} of {suit}" for rank, suit in hand))
# Main game loop
def play_blackjack():
deck = create_deck()
player_hand = [deck.pop(), deck.pop()]
dealer_hand = [deck.pop(), deck.pop()]
print("\n=== Blackjack Game ===")
display_hand(player_hand)
display_hand(dealer_hand, hidden=True)
# Player turn
while True:
player_value = calculate_hand(player_hand)
print(f"Your hand value: {player_value}")
if player_value > 21:
print("You busted! Dealer wins.")
return
move = input("Hit or Stand? (h/s): ").strip().lower()
if move == 'h':
player_hand.append(deck.pop())
display_hand(player_hand)
elif move == 's':
break
else:
print("Invalid input. Please type 'h' or 's'.")
# Dealer turn
print("\nDealer's turn:")
display_hand(dealer_hand)
while calculate_hand(dealer_hand) < 17:
dealer_hand.append(deck.pop())
display_hand(dealer_hand)
dealer_value = calculate_hand(dealer_hand)
player_value = calculate_hand(player_hand)
print(f"\nYour final hand: {player_value}")
print(f"Dealer's final hand: {dealer_value}")
# Determine outcome
if dealer_value > 21 or player_value > dealer_value:
print("You win!")
elif dealer_value == player_value:
print("It's a tie!")
else:
print("Dealer wins!")
# Start the game
if __name__ == "__main__":
play_blackjack()
import random
def play_game():
print("Welcome to Rock, Paper, Scissors!")
options = ["rock", "paper", "scissors"]
while True:
user_choice = input("Choose rock, paper, or scissors (or type 'quit' to exit): ").lower()
if user_choice == "quit":
print("Thanks for playing!")
break
if user_choice not in options:
print("Invalid choice. Try again.")
continue
computer_choice = random.choice(options)
print(f"Computer chose: {computer_choice}")
if user_choice == computer_choice:
print("It's a tie!")
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "paper" and computer_choice == "rock") or \
(user_choice == "scissors" and computer_choice == "paper"):
print("You win!")
else:
print("You lose!")
print()
# Run the game
play_game()
import string
import random
def starting_sequence():
print("Hi! this is a password generator, \n it helps make unique, random, and convenient passwords for you to use!")
def password_generate(length):
char = list(string.ascii_lowercase)
password = []
for i in range(length):
password.append(random.choice(char))
password.append(random.randint(0, 9))
for i in range(length):
password.pop()
print("your password is: ", password)
while True:
starting_sequence()
pass_length = int(input("how long should it be: "))
password_generate(pass_length)
import pygame
import random
import sys
pygame.init()
SW = 1280
SH = 720
FONT = pygame.font.SysFont("consolas", int(SW/20))
SCREEN = pygame.display.set_mode((SW, SH))
pygame.display.set_caption("Pong Project")
CLOCK = pygame.time.Clock()
# Paddle's (p1 and p2)
player1 = pygame.Rect(SW - 110, SH / 2-50, 10, 100)
player2 = pygame.Rect(110, SH / 2-50, 10, 100)
player1_score, player2_score = 0, 0
# Ball
ball = pygame.Rect(SW/2 - 10, SH/2 - 10, 20, 20)
x_speed, y_speed = 1, 1
while True:
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_UP]:
if player1.top > 0:
player1.top -= 2
if keys_pressed[pygame.K_DOWN]:
if player1.bottom < SH:
player1.bottom += 2
if keys_pressed[pygame.K_w]:
if player2.top > 0:
player2.top -= 2
if keys_pressed[pygame.K_s]:
if player2.bottom < SH:
player2.bottom += 2
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if ball.y > SH:
y_speed = -1
if ball.y <= 0:
y_speed = 1
if ball.x <= 0:
player1_score += 1
ball.center = (SW / 2, SH / 2)
x_speed, y_speed = random.choice([1, -1]), random.choice([1, -1])
if ball.x >= SW:
player2_score += 1
ball.center = (SW / 2, SH / 2)
x_speed, y_speed = random.choice([1, -1]), random.choice([1, -1])
if player1.x - ball.width <= ball.x <= player1.x and ball.y in range(player1.top - ball.width, player1.bottom + ball.width):
x_speed = -1
if player2.x - ball.width <= ball.x <= player2.x and ball.y in range(player2.top - ball.width, player2.bottom + ball.width):
x_speed = 1
ball.x += x_speed * 2
ball.y += y_speed * 2
player1_score_text = FONT.render(str(player1_score), True, "white")
player2_score_text = FONT.render(str(player2_score), True, "white")
SCREEN.fill("black")
pygame.draw.rect(SCREEN, "white", player1)
pygame.draw.rect(SCREEN, "white", player2)
pygame.draw.circle(SCREEN, "white", ball.center, 10)
SCREEN.blit(player1_score_text, (SW/2+50, 50))
SCREEN.blit(player2_score_text, (SW/2-50, 50))
pygame.display.update()
CLOCK.tick(300)
import pygame
import sys
import random
SW, SH = 900, 900
BLOCK_SIZE = 50
screen = pygame.display.set_mode((SW, SH))
pygame.display.set_caption("Snake :)")
clock = pygame.time.Clock()
class Snake:
def __init__(self):
self.x, self.y = BLOCK_SIZE, BLOCK_SIZE
self.xdir = 1
self.ydir = 0
self.head = pygame.Rect(self.x, self.y, BLOCK_SIZE, BLOCK_SIZE)
self.body = [pygame.Rect(self.x-BLOCK_SIZE, self.y, BLOCK_SIZE, BLOCK_SIZE)]
self.dead = False
def update(self):
global lemon
for square in self.body:
if self.head.x == square.x and self.head.y == square.y:
self.dead = True
if self.head.x not in range(0, SW) or self.head.y not in range(0, SH):
self.dead = True
if self.dead:
self.x, self.y = BLOCK_SIZE, BLOCK_SIZE
self.head = pygame.Rect(self.x, self.y, BLOCK_SIZE, BLOCK_SIZE)
self.body = [pygame.Rect(self.x-BLOCK_SIZE, self.y, BLOCK_SIZE, BLOCK_SIZE)]
self.xdir = 1
self.ydir= 0
self.dead = False
lemon = Lemon()
self.body.append(self.head)
for i in range(len(self.body)-1):
self.body[i].x, self.body[i].y = self.body[i+1].x, self.body[i+1].y
self.head.x += self.xdir * BLOCK_SIZE
self.head.y += self.ydir * BLOCK_SIZE
self.body.remove(self.head)
class Lemon:
def __init__(self):
self.x = int(random.randint(0, SW) / BLOCK_SIZE) * BLOCK_SIZE
self.y = int(random.randint(0, SH) / BLOCK_SIZE) * BLOCK_SIZE
self.rect = pygame.Rect(self.x, self.y, BLOCK_SIZE, BLOCK_SIZE)
def update(self):
pygame.draw.rect(screen, "yellow", self.rect)
def draw_grid():
for x in range(0, SW, BLOCK_SIZE):
for y in range(0, SH, BLOCK_SIZE):
rect = pygame.Rect(x, y, BLOCK_SIZE, BLOCK_SIZE)
pygame.draw.rect(screen, "#3c3c3b", rect, 1)
draw_grid()
snake = Snake()
lemon = Lemon()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
snake.ydir = 1
snake.xdir = 0
elif event.key == pygame.K_UP:
snake.ydir = -1
snake.xdir = 0
elif event.key == pygame.K_RIGHT:
snake.ydir = 0
snake.xdir = 1
elif event.key == pygame.K_LEFT:
snake.ydir = 0
snake.xdir = -1
snake.update()
screen.fill('black')
draw_grid()
lemon.update()
pygame.draw.rect(screen, "green", snake.head)
for square in snake.body:
pygame.draw.rect(screen, "green", square)
if snake.head.x == lemon.x and snake.head.y == lemon.y:
snake.body.append(pygame.Rect(square.x, square.y, BLOCK_SIZE, BLOCK_SIZE))
lemon = Lemon()
pygame.display.update()
clock.tick(10)
import pygame
import sys
pygame.init()
#Constants
WIDHT, HEIGHT = 800,800
SQUARE_SIZE = WIDHT//8
#colors
WHITE =(255,255,255)
BLACK = (0,0,0)
BROWN = (139,69,19)
YELLOW = (255,255,0)
#create the screen
screen = pygame.display.set_mode((WIDHT,HEIGHT))
pygame.display.set_caption("Chess Game")
#Chess piece class
class ChessPiece:
def __init__(self,color,type,image):
self.color=color
self.type = type
self.image = pygame.image.load(image)
self.image = pygame.transform.scale(self.image, (SQUARE_SIZE,SQUARE_SIZE))
self.has_moved = False
#Initialize the board
board = [[None for _ in range(8)] for _ in range(8)]
#Current Player
current_player = 'white'
#selected piece
selected_piece = None
selected_pos = None
def init_board():
#Pawns
for col in range(8):
board[1][col] = ChessPiece ('black','pawn','images/black_pawn.png')
board[6][col] = ChessPiece ('white','pawn','images/white_pawn.png')
#Rooks
board[0][0] = board[0][7] = ChessPiece('black','rook','images/black_rook.png')
board[7][0] = board[7][7] = ChessPiece('white', 'rook','images/white_rook.png')
# Knights
board[0][1] = board[0][6] = ChessPiece('black', 'knight', 'images/black_knight.png')
board[7][1] = board[7][6] = ChessPiece('white', 'knight', 'images/white_knight.png')
# Bishops
board[0][2] = board[0][5] = ChessPiece('black', 'bishop', 'images/black_bishop.png')
board[7][2] = board[7][5] = ChessPiece('white', 'bishop', 'images/white_bishop.png')
# Queens
board[0][3] = ChessPiece('black', 'queen', 'images/black_queen.png')
board[7][3] = ChessPiece('white', 'queen', 'images/white_queen.png')
# Kings
board[0][4] = ChessPiece('black', 'king', 'images/black_king.png')
board[7][4] = ChessPiece('white', 'king', 'images/white_king.png')
#Function to draw the board
def draw_board():
for row in range(8):
for col in range(8):
color = WHITE if (row + col) % 2 ==0 else BROWN
pygame.draw.rect(screen,color,(col* SQUARE_SIZE ,row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
if selected_pos:
pygame.draw.rect(screen,YELLOW,(selected_pos[1]*SQUARE_SIZE,selected_pos[0]*SQUARE_SIZE,SQUARE_SIZE,SQUARE_SIZE))
#Function to draw the pieces
def draw_piece():
for row in range(8):
for col in range(8):
piece = board[row][col]
if piece:
screen.blit(piece.image,(col*SQUARE_SIZE, row*SQUARE_SIZE))
# Function to get valid moves for a piece
def get_valid_moves(piece, row, col):
moves = []
if piece.type == 'pawn':
direction = -1 if piece.color == 'white' else 1
if 0 <= row + direction < 8 and board[row + direction][col] is None:
moves.append((row + direction, col))
if (piece.color == 'white' and row == 6) or (piece.color == 'black' and row == 1):
if board[row + 2*direction][col] is None:
moves.append((row + 2*direction, col))
for dc in [-1, 1]:
if 0 <= row + direction < 8 and 0 <= col + dc < 8:
if board[row + direction][col + dc] and board[row + direction][col + dc].color != piece.color:
moves.append((row + direction, col + dc))
elif piece.type == 'rook':
for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
r, c = row + dr, col + dc
while 0 <= r < 8 and 0 <= c < 8:
if board[r][c] is None:
moves.append((r, c))
elif board[r][c].color != piece.color:
moves.append((r, c))
break
else:
break
r, c = r + dr, c + dc
elif piece.type == 'knight':
for dr, dc in [(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)]:
r, c = row + dr, col + dc
if 0 <= r < 8 and 0 <= c < 8 and (board[r][c] is None or board[r][c].color != piece.color):
moves.append((r, c))
elif piece.type == 'bishop':
for dr, dc in [(1, 1), (1, -1), (-1, 1), (-1, -1)]:
r, c = row + dr, col + dc
while 0 <= r < 8 and 0 <= c < 8:
if board[r][c] is None:
moves.append((r, c))
elif board[r][c].color != piece.color:
moves.append((r, c))
break
else:
break
r, c = r + dr, c + dc
elif piece.type == 'queen':
for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]:
r, c = row + dr, col + dc
while 0 <= r < 8 and 0 <= c < 8:
if board[r][c] is None:
moves.append((r, c))
elif board[r][c].color != piece.color:
moves.append((r, c))
break
else:
break
r, c = r + dr, c + dc
elif piece.type == 'king':
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
if dr == 0 and dc == 0:
continue
r, c = row + dr, col + dc
if 0 <= r < 8 and 0 <= c < 8 and (board[r][c] is None or board[r][c].color != piece.color):
moves.append((r, c))
return moves
#Function to check if the king is in check
def is_check(color):
king_pos = None
for r in range(8):
for c in range(8):
if board[r][c] and board[r][c].color == color and board[r][c]=='king':
king_pos = (r,c)
break
if king_pos:
break
for r in range(8):
for c in range(8):
piece = board[r][c]
if piece and piece.color != color:
if king_pos in get_valid_moves(piece,r,c):
return True
return False
#function to check for checkmate
def is_game_over():
for r in range(8):
for c in range(8):
piece = board[r][c]
if piece and piece.color == current_player:
valid_moves = get_valid_moves(piece,r,c)
for move in valid_moves:
#Try the move
temp = board[move[0]][move[1]]
board[move[0]][move[1]] = piece
board[r][c]= None
check = is_check(current_player)
#undo the move
board[r][c]= piece
board[move[0]][move[1]] =temp
if not check:
return False
return True
# Function to handle mouse clicks
def handle_click(pos):
global selected_piece, selected_pos, current_player
col = pos[0] // SQUARE_SIZE
row = pos[1] // SQUARE_SIZE
if selected_piece is None:
piece = board[row][col]
if piece and piece.color == current_player:
selected_piece = piece
selected_pos = (row, col)
else:
if (row, col) in get_valid_moves(selected_piece, selected_pos[0], selected_pos[1]):
# Move the piece
board[row][col] = selected_piece
board[selected_pos[0]][selected_pos[1]] = None
selected_piece.has_moved = True
# Check for pawn promotion
if selected_piece.type == 'pawn' and (row == 0 or row == 7):
board[row][col] = ChessPiece(selected_piece.color, 'queen', f'images/{selected_piece.color}_queen.png')
# Switch turns
current_player = 'black' if current_player == 'white' else 'white'
# Check for game over
if is_game_over():
if is_check(current_player):
print(f"Checkmate! {current_player.capitalize()} loses.")
else:
print("Stalemate!")
selected_piece = None
selected_pos = None
#Main game loop
def main():
init_board()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
handle_click(pygame.mouse.get_pos())
draw_board()
draw_piece()
pygame.display.flip()
if __name__ == "__main__":
main()
Free to use GDscript code:
import random
extends CharacterBody2D
# variables and constants
const speed = 550
const jump_force = -2600
var gravity = 100
var input_dir = 0
var max_jump = 2
var jump_count = 0
var direction = 0
const accelerate = 60
const friction = 70
# physics
func _physics_process(_delta):
# for going back to the menu
if Input.is_action_pressed("Menu"):
get_tree().change_scene_to_file("res://scenes/menu.tscn")
# for resetting the scene
if Input.is_action_pressed("Reset"):
get_tree().reload_current_scene()
# jump and double jump
if is_on_floor() and jump_count != 0:
jump_count = 0
if is_on_wall() and jump_count != 0:
jump_count = 0
if jump_count < max_jump:
if Input.is_action_just_pressed("ui_up"):
velocity.y = jump_force
jump_count += 1
look_dir()
wall_climb()
var input_dir: Vector2 = input()
gravity_handle()
if input_dir != Vector2.ZERO:
acc(input_dir)
else:
add_friction()
if is_on_floor():
var current_jumps = 0
player_movement()
# physics stuff
func input() -> Vector2:
var input_dir = Vector2.ZERO
input_dir.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
input_dir = input_dir.normalized()
return input_dir
func acc(direction):
velocity = velocity.move_toward(speed * direction, accelerate)
func add_friction():
velocity = velocity.move_toward(Vector2.ZERO, friction)
func player_movement():
move_and_slide()
func gravity_handle():
velocity.y += gravity
func look_dir():
if Input.is_action_pressed("ui_right"):
$Sprite2D.flip_h = true
if Input.is_action_pressed("ui_left"):
$Sprite2D.flip_h = false
func wall_climb():
# wall cling
if is_on_wall():
if Input.is_action_pressed("ui_right"):
velocity.y = 0
gravity = 0
if Input.is_action_pressed("ui_up"):
velocity.y += jump_force * 0.5
if Input.is_action_pressed("ui_down"):
velocity.y += -jump_force * 0.5
if Input.is_action_pressed("ui_left"):
velocity.y = 0
gravity = 0
if Input.is_action_pressed("ui_up"):
velocity.y += jump_force * 0.5
if Input.is_action_pressed("ui_down"):
velocity.y += -jump_force * 0.5
if !is_on_wall():
gravity = 100
func _on_killzone_body_entered(_body):
get_tree().reload_current_scene()
extends Node
var states = {}
var current_state = null
func _ready():
# Register all states
states = {
"Idle": preload("res://states/IdleState.gd").new(),
"Walk": preload("res://states/WalkState.gd").new(),
"Attack": preload("res://states/AttackState.gd").new(),
}
# Initialize the starting state
change_state("Idle")
func _process(delta):
if current_state and current_state.has_method("update"):
current_state.update(delta)
func _physics_process(delta):
if current_state and current_state.has_method("physics_update"):
current_state.physics_update(delta)
func change_state(state_name: String):
if current_state and current_state.has_method("exit"):
current_state.exit()
current_state = states.get(state_name)
if current_state and current_state.has_method("enter"):
current_state.enter()
Example usage for a state:
extends Node
func enter():
print("Entering Idle State")
func update(delta):
# Check for input or conditions to change state
if Input.is_action_pressed("ui_right"):
get_parent().change_state("Walk")
func exit():
print("Exiting Idle State")
My AI that I'm developing:
ChatSPT
from transformers import pipeline
# Initialize the chatbot with the GPT-2 model
chatbot = pipeline("text-generation", model="gpt2")
print("Hello! I'm your GPT-2 chatbot. Type 'quit' to exit.")
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
print("Goodbye!")
break
# Generate response from GPT-2
response = chatbot(user_input, max_length=50, do_sample=True, temperature=0.7)
# Extract the generated text
bot_response = response[0]['generated_text']
# Print the response
print("Bot:", bot_response[len(user_input):].strip()) # Remove input from the response