用AI寫游戲3——deepseek實現kotlin android studio greedy snake game 貪吃蛇游戲

項目下載

https://download.csdn.net/download/AnalogElectronic/90421306
在這里插入圖片描述

項目結構

在這里插入圖片描述
就是通過android studio 建空項目,改下MainActivity.kt的內容就完事了

ctrl+shift+alt+s 看項目結構如下
在這里插入圖片描述

核心代碼

MainActivity.kt

package com.example.snakegame1// MainActivity.kt
import android.content.ContentValues.TAG
import android.view.KeyEvent
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.*
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import java.util.*
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
import kotlin.math.abs
import kotlin.math.roundToInt// 游戲配置常量
const val CELL_SIZE = 30f      // 每個網格單元大小
const val GRID_SIZE = 20       // 網格行列數
const val GAME_SPEED = 150L    // 游戲刷新速度(毫秒)// 方向枚舉類
enum class Direction { UP, DOWN, LEFT, RIGHT }// 坐標數據類
data class Point(val x: Int, val y: Int)class MainActivity : ComponentActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent {SnakeGame()}}
}@Composable
fun SnakeGame() {// 游戲狀態控制var isPlaying by remember { mutableStateOf(true) }var score by remember { mutableStateOf(0) }Log.d(TAG, "游戲是否啟動: $isPlaying")// 蛇的初始狀態val snake = remember {mutableStateOf(Snake(body = listOf(Point(GRID_SIZE/2, GRID_SIZE/2)),direction = Direction.RIGHT))}// 食物位置var food by remember { mutableStateOf(generateFood(snake.value.body)) }// 游戲循環控制LaunchedEffect(key1 = isPlaying) {while (isPlaying) {delay(GAME_SPEED)snake.value = snake.value.move()// 檢測是否吃到食物if (snake.value.body.first() == food) {score += 10food = generateFood(snake.value.body)snake.value = snake.value.grow()}// 檢測碰撞if (checkCollision(snake.value.body)) {isPlaying = false}}}Column(modifier = Modifier.fillMaxSize().background(Color(0xFF2B2B2B)).pointerInput(Unit) {// 處理觸摸或鼠標事件detectDragGestures { _, dragAmount ->// 根據拖動方向改變蛇的方向if (abs(dragAmount.x) > abs(dragAmount.y)) {if (dragAmount.x > 0) {snake.value = snake.value.turn(Direction.RIGHT)} else {snake.value = snake.value.turn(Direction.LEFT)}} else {if (dragAmount.y > 0) {snake.value = snake.value.turn(Direction.DOWN)} else {snake.value = snake.value.turn(Direction.UP)}}}}.focusable(),verticalArrangement = Arrangement.Center,horizontalAlignment = Alignment.CenterHorizontally) {// 游戲畫布Canvas(modifier = Modifier.size((CELL_SIZE * GRID_SIZE).dp).background(Color.Black)) {// 繪制網格線for (i in 0..GRID_SIZE) {drawLine(color = Color.Gray.copy(alpha = 0.3f),start = Offset(i * CELL_SIZE, 0f),end = Offset(i * CELL_SIZE, size.height),strokeWidth = 1f)drawLine(color = Color.Gray.copy(alpha = 0.3f),start = Offset(0f, i * CELL_SIZE),end = Offset(size.width, i * CELL_SIZE),strokeWidth = 1f)}// 繪制食物drawCircle(color = Color.Red,center = Offset(food.x * CELL_SIZE + CELL_SIZE / 2,food.y * CELL_SIZE + CELL_SIZE / 2),radius = CELL_SIZE / 3)// 繪制蛇身snake.value.body.forEachIndexed { index, point ->val color = if (index == 0) Color.Green else Color(0xFF4CAF50)drawCircle(color = color,center = Offset(point.x * CELL_SIZE + CELL_SIZE / 2,point.y * CELL_SIZE + CELL_SIZE / 2),radius = CELL_SIZE / 2.5f,style = Stroke(width = 3f))}}// 重新開始按鈕if (!isPlaying) {Button(onClick = {// 重置游戲狀態isPlaying = truescore = 0snake.value = Snake(body = listOf(Point(GRID_SIZE/2, GRID_SIZE/2)),direction = Direction.RIGHT)food = generateFood(snake.value.body)},modifier = Modifier.padding(8.dp)) {Text("重新開始")}}}
}// 蛇類定義
class Snake(val body: List<Point>,val direction: Direction
) {// 移動方法fun move(): Snake {val head = body.first()val newHead = when (direction) {Direction.UP -> head.copy(y = head.y - 1)Direction.DOWN -> head.copy(y = head.y + 1)Direction.LEFT -> head.copy(x = head.x - 1)Direction.RIGHT -> head.copy(x = head.x + 1)}return copy(body = listOf(newHead) + body.dropLast(1))}// 轉向方法fun turn(newDirection: Direction): Snake {// 禁止反向移動if ((direction == Direction.UP && newDirection == Direction.DOWN) ||(direction == Direction.DOWN && newDirection == Direction.UP) ||(direction == Direction.LEFT && newDirection == Direction.RIGHT) ||(direction == Direction.RIGHT && newDirection == Direction.LEFT)) {return this}return copy(direction = newDirection)}// 增長方法fun grow(): Snake {val tail = body.last()val newTail = when (direction) {Direction.UP -> tail.copy(y = tail.y + 1)Direction.DOWN -> tail.copy(y = tail.y - 1)Direction.LEFT -> tail.copy(x = tail.x + 1)Direction.RIGHT -> tail.copy(x = tail.x - 1)}return copy(body = body + newTail)}private fun copy(body: List<Point> = this.body,direction: Direction = this.direction) = Snake(body, direction)
}// 生成食物位置
fun generateFood(snakeBody: List<Point>): Point {val random = Random()while (true) {val newFood = Point(random.nextInt(GRID_SIZE),random.nextInt(GRID_SIZE))if (newFood !in snakeBody) return newFood}
}// 碰撞檢測
fun checkCollision(body: List<Point>): Boolean {val head = body.first()return head.x < 0 || head.x >= GRID_SIZE ||head.y < 0 || head.y >= GRID_SIZE ||head in body.drop(1)
}

實現效果
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/70514.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/70514.shtml
英文地址,請注明出處:http://en.pswp.cn/web/70514.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【數據庫系統概論】數據庫設計

7.1 數據庫設計概述 定義 數據庫設計是指對于一個給定的應用環境&#xff0c;構造&#xff08;設計&#xff09; 優化的 數據庫模式、內模式和外模式&#xff0c;并據此建立數據庫及其 應用系統 &#xff0c;使之能夠有效地存儲和管理數據&#xff0c;滿足各種用戶的應用需求…

Element UI日期選擇器默認顯示1970年解決方案

目錄 問題背景 問題根源 1. 數據綁定類型錯誤 2. 初始化邏輯錯誤 解決方案 核心思路 步驟 1&#xff1a;正確初始化日期對象 步驟 2&#xff1a;處理數據交互 步驟 3&#xff1a;處理年份切換事件 完整代碼示例 注意事項 1. 時區問題 2. 格式化綁定值 常見問題 1. 為什…

kafka-保姆級配置說明(producer)

配置說明的最后一部分&#xff1b; ##指定kafka集群的列表&#xff0c;以“,”分割&#xff0c;格式&#xff1a;“host:port,host:port” ##此列表用于producer&#xff08;consumer&#xff09;初始化連接使用&#xff0c;server列表可以為kafka集群的子集 ##通過此servers列…

.NET周刊【2月第2期 2025-02-09】

國內文章 開箱即用的.NET MAUI組件庫 V-Control 發布了! https://www.cnblogs.com/jevonsflash/p/18701494 文章介紹了V-Control&#xff0c;一個適用于.NET MAUI的組件庫。作者計劃將其開源&#xff0c;強調.NET MAUI是生產力強的跨平臺移動開發工具。V-Control提供多種組件…

PHP2(WEB)

##解題思路 打開頁面什么線索都沒有&#xff0c;目錄掃描只是掃出來一個index.php&#xff0c;而源代碼沒有東西&#xff0c;且/robots.txt是不允許訪問的 于是一番查詢后發現&#xff0c;有個index.phps的文件路徑&#xff0c;里頭寫著一段php的邏輯&#xff0c;對url的id參數…

VisActor/VTable - 快速搭建表格

VTable源于VisActor體系&#xff0c;該體系是從字節跳動大量可視化場景沉淀而來&#xff0c;旨在提供面向敘事的智能可視化解決方案。VisActor包括渲染引擎、可視化語法、數據分析組件、圖表組件、表格組件、GIS組件、圖可視化組件、智能組件等多個模塊&#xff0c;以及周邊生態…

c++第一課(基礎c)

目錄 1.開場白 2.char&#xff08;字符&#xff09; 3.字符數組 4.ASCII碼 1.開場白 OK&#xff0c;咱們也是億&#xff08;不是作者故意的&#xff09;天沒見&#xff0c;話不多說&#xff0c;直接開始&#xff01; 2.char&#xff08;字符&#xff09; 眾所不周知&…

2025年02月21日Github流行趨勢

項目名稱&#xff1a;source-sdk-2013 項目地址url&#xff1a;https://github.com/ValveSoftware/source-sdk-2013項目語言&#xff1a;C歷史star數&#xff1a;7343今日star數&#xff1a;929項目維護者&#xff1a;JoeLudwig, jorgenpt, narendraumate, sortie, alanedwarde…

【簡單】209.長度最小的子數組

題目描述 給定一個含有 n 個正整數的數組和一個正整數 target 。 找出該數組中滿足其總和大于等于 target 的長度最小的 子數組 [numsl, numsl1, …, numsr-1, numsr] &#xff0c;并返回其長度。如果不存在符合條件的子數組&#xff0c;返回0。 示例 1&#xff1a; 輸入&am…

【STM32】內存管理

【STM32】內存管理 文章目錄 【STM32】內存管理1、內存管理簡介疑問&#xff1a;為啥不用標準的 C 庫自帶的內存管理算法&#xff1f;2、分塊式內存管理&#xff08;掌握&#xff09;分配方向分配原理釋放原理分塊內存管理 管理內存情況 3、內存管理使用&#xff08;掌握&#…

Linux 命令大全完整版(14)

5. 文件管理命令 chgrp(change group) 功能說明&#xff1a;變更文件或目錄的所屬群組。語  法&#xff1a;chgrp [-cfhRv][–help][–version][所屬群組][文件或目錄…] 或 chgrp [-cfhRv][–help][–version][–reference<參考文件或目錄>][文件或目錄…]補充說明&…

[數據結構]順序表詳解

目錄 一.線性表 二.順序表 2.1概念及結構 1. 靜態順序表&#xff1a;使用定長數組存儲元素。 2. 動態順序表&#xff1a;使用動態開辟的數組存儲。 2.1按需申請 2.2 接口實現&#xff1a;增刪查改 SeqList.h: SeqList.c: test.c 一.線性表 線性表 &#xff08; line…

綫性與非綫性泛函分析與應用_2.賦范向量空間-母本

第2章 賦范向量空間 1.向量空間;哈默爾基;向量空間的維數 - 定義與性質 - 向量空間的定義:設\mathbb{K}為數域,集合X是\mathbb{K}上的向量空間,若在X上定義了加法(x,y)\in X\times X\to x + y\in X和數乘(\alpha,x)\in\mathbb{K}\times X\to\alpha x\in X兩種運算,且滿足…

2025年- G17-Lc91-409.最長回文-java版

1.題目描述 2.思路 思路1: 判斷一個字符串中的字母個數是否是偶數個。 遍歷字符串&#xff0c;檢查每個字符是否是字母&#xff08;可以通過 Character.isLetter() 來判斷&#xff09;。 累加字母的個數。 最后判斷字母的個數是否是偶數。 思路2: 這段 Java 代碼的作用是 統…

SpringBoot+Mybatis-Plus實現動態數據源

目錄 一、前言二、代碼實現1&#xff09;工程結構2&#xff09;相關依賴3&#xff09;數據源攔截切面4&#xff09;動態數據源切換5&#xff09;核心配置類6&#xff09;使用 三、原理分析1&#xff09;mapper接口注入流程2&#xff09;動態數據源切換執行流程 四、聲明式事務導…

玩轉 Java 與 Python 交互,JEP 庫來助力

文章目錄 玩轉 Java 與 Python 交互&#xff0c;JEP 庫來助力一、背景介紹二、JEP 庫是什么&#xff1f;三、如何安裝 JEP 庫&#xff1f;四、JEP 庫的簡單使用方法五、JEP 庫的實際應用場景場景 1&#xff1a;數據處理場景 2&#xff1a;機器學習場景 3&#xff1a;科學計算場…

Qt常用控件之日歷QCalendarWidget

日歷QCalendarWidget QCalendarWidget 是一個日歷控件。 QCalendarWidget屬性 屬性說明selectDate當前選中日期。minimumDate最小日期。maximumDate最大日期。firstDayOfWeek設置每周的第一天是周幾&#xff08;影響日歷的第一列是周幾&#xff09;。gridVisible是否顯示日歷…

三數之和:經典問題的多種優化策略

三數之和&#xff1a;經典問題的多種優化策略 大家好&#xff0c;我是Echo_Wish。今天我們來聊一個經典的算法問題——三數之和&#xff08;3Sum&#xff09;。它是許多面試和算法競賽中常見的問題之一&#xff0c;也常常考察我們對算法優化的理解和技巧。我們不僅要解決問題&…

Go 語言中的協程

概念 Go語言中的協程&#xff08;Goroutine&#xff09;是一種由Go運行時管理的輕量級線程。它是Go語言并發模型的核心&#xff0c;旨在通過簡單、易用的方式支持高并發的程序設計。 創建協程 協程的創建非常簡單&#xff0c;只需要使用go關鍵字&#xff0c;后面跟著一個函數…

JAVA最新版本詳細安裝教程(附安裝包)

目錄 文章自述 一、JAVA下載 二、JAVA安裝 1.首先在D盤創建【java/jdk-23】文件夾 2.把下載的壓縮包移動到【jdk-23】文件夾內&#xff0c;右鍵點擊【解壓到當前文件夾】 3.如圖解壓會有【jdk-23.0.1】文件 4.右鍵桌面此電腦&#xff0c;點擊【屬性】 5.下滑滾動條&…